# 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("不存在")

用递归方法实现二分法:

"""

1: 函数开始前,要先判断满足条件, 左索引值要小于右索引值
2: 就是比较之后, 左右索引要移动到中间值的前一位或者后一位索引位置上
"""
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) )


------问题-------
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]
######## 拆分讲解
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循环那一刻可以缩写代码如下

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)

05-08 262

02-06 523
05-07 1049
07-17 4584
08-27 2240
11-20 643
03-05 2114
12-01 857