Python(二分法查找)

  • 专业分析二分法查找

  •  二分法针对的对象要是有序的队列,通过索引找到你要查找的值
  •  思想:取一个索引开头left,取一个索引末尾(len(队列)-1)right,让你的值跟(left + right)//2(middle)比
  • 如果索引middle值比你查的值大,把middle赋值给right,反之把middle赋值给left;
  • 代码展示:
  • lst = [11,22,33,44,55,66,77,88,99,123,234,345,456,567,678,789,1111]
    n = 456
    left = 0
    right = len(lst) - 1
    count = 1
    while left <= right:
        middle = (left + right) // 2
        if n > lst[middle]:
            left = middle + 1
        elif n < lst[middle]:
            right = middle - 1
        else:
            print('查找次数%s' % count)
            print("存在位置%s" % middle)
            break
        count = count + 1
    else:
        print("不存在")

    用递归方法实现二分法:

def binary_search(left, right, n):
    middle = (left + right)//2
    if left > right:
        return -1
    if n > lst[middle]:
        left = middle + 1
    elif n < lst[middle]:
        right = middle - 1
    else:
        return middle
    return binary_search(left, right, n)
print(binary_search(0, len(lst)-1, 65) )

迭代器50000000000000000星级难题

------问题-------
def add(a, b):
    return a + b


def test():
    for i in range(4):
        yield i


g = test()
for n in [2,10]:
    g = (add(n,i) for i in g)
print(list(g))  #[20,21,22,23]
######## 拆分讲解
def add(a, b):
    return a + b


def test():
    for i in range(4):
        yield i

g = test()

#-----循环体
for n in [2,10]:
    g = (add(n,i) for i in g)
print(list(g))

#-----对循环体拆分
# n=2时
n = 2
g = (add(n, i) for i in g) 
# n=10时
n = 10
g = (add(n, i) for i in g)


# -----所以for循环那一刻可以缩写代码如下
g = (add(n,i) for i in (add(n,i) for i in test()))
所以在一直没有list(g)取值时,生成器只会先生成表达式,只有要值了,才会把test()带进去值

62进制的问题:

s1 = ''.join([chr(i) for i in range(65,90)])
s2 = ''.join([chr(i) for i in range(97,122)])
s3 = ''.join([str(i) for i in range(10)])
s = s3+s1+s2
res = ''
while n!=0:
    ord_ = n%62
    n = n//62
    res += s[ord_]
print(res)

 

你可能感兴趣的:(python小坑小闹)