我有一个程序,它使用二进制搜索。 最后,我需要打印一个循环计数。 如何做得更好?
import re
def binarySearch(sumList, whattofind):
a=0
if len(sumList) == 0:
return False
else:
midpoint = len(sumList)/2
if sumList[midpoint]==whattofind:
a=a+1
print(a)
return True
else:
if whattofind<sumList[midpoint]:
a+=1
return binarySearch(sumList[:midpoint],whattofind)
else:
a+=1
return binarySearch(sumList[midpoint+1:],whattofind)
print(a)
result = re.findall(r'\w\w', open("text.txt","r").read())
sumList=[]
for line in result:
sumList.append(ord(line[0])+ord(line[1]))
sumList.sort()
whattofind=int(input('Enter number: '))
print (sumList)
print(binarySearch(sumList, whattofind))
答案 0 :(得分:1)
执行以下操作
count = 0
def binarySearch(sumList, whattofind):
global count
count += 1
并且在最后一行代码中只打印count
的值