# find out a character in the given sorted list
input_list = ['2', '6', '9', '11', '15', '30', '54']
input_char = raw_input('Enter a char: ')
def bin_search(input_char):
start = 0
end = len(input_list) - 1
while start <= end:
mid = (start + end) / 2
if input_char == input_list[mid]:
print 'Character ' + str(input_char) + ' found'
return input_char
elif input_char > input_list[mid]:
start = mid + 1
elif input_char < input_list[mid]:
end = mid - 1
else:
print 'Character not found'
return
print bin_search(input_char)
答案 0 :(得分:1)
二进制搜索需要您搜索的列表进行排序。
由于值是字符串,因此列表当前未排序
>>> input_list = ['2', '6', '9', '11', '15', '30', '54']
>>> sorted(input_list)
['11', '15', '2', '30', '54', '6', '9']
如果您想进行数字搜索,最好将所有内容转换为数字