我正在为书本电话编写二进制搜索树。问题是当我尝试编写主代码时。我试图使用字典数据结构,但我无法弄清楚如何将联系人姓名作为关键。我想写任何名字,并将电话号码作为值。
它给了我一个错误
Traceback (most recent call last):
File "FastSort.py", line 22, in <module>
print(binarySearch(phonebook, "John"))
File "FastSort.py", line 8, in binarySearch
if alist[midpoint] == item:
KeyError: 1
这是一个代码
def binarySearch(alist, item):
first = 0
last = len(alist)-1
found = False
while first<=last and not found:
midpoint = (first + last)//2
if alist[midpoint] == item:
found = True
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return found
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(binarySearch(phonebook, "John"))
print(binarySearch(phonebook, "Jack"))
答案 0 :(得分:1)
你的解决方案(如果import random
def binarySearch(alist, item):
first = 0
last = len(alist)-1
while first<=last:
midpoint = (first + last)//2
print midpoint
if alist[midpoint][0] == item:
return alist[midpoint]
else:
if item < alist[midpoint][0]:
last = midpoint-1
else:
first = midpoint+1
return False
items = []
items.append(("John", 938477566))
items.append(("Jack", 938377264))
items.append(("Jill", 947662781))
items = sorted(items)
print(binarySearch(items, "John"))
print(binarySearch(items, "Jack"))
print(binarySearch(items, "Jill"))
实际上是一个排序列表)非常接近,所以我想我会帮助你一点:
{{1}}