前綴字符串二進制搜索我有一個測試工具,出於某種原因,這個代碼是在發現前綴失敗,也忽略了短詞。任何建議/提示/想法?在一個dict.txt文件
def search(str):
"""Search for a prefix string in the dictionary.
Args:
str: A string to look for in the dictionary
Returns:
code WORD if str exactly matches a word in the dictionary,
PREFIX if str does not match a word exactly but is a prefix
of a word in the dictionary, or
NO_MATCH if str is not a prefix of any word in the dictionary
"""
left = 0
right = len(dict) - 1
mid = (left + right) // 2
elem = dict[mid]
while right >= left:
if elem == str:
return WORD
elif elem < str:
left = mid + 1
mid = (left + right) // 2
elif elem > str:
right = mid - 1
mid = (left + right) // 2
elif elem == str[0:len(elem)]:
return PREFIX
elem = dict[mid]
#print(left, right, mid)
return NO_MATCH
我認爲前綴總是會小於一個完整的字符串,所以最後elif不會被擊中 – noisecapella
dict()是內建的,喲你應該避免命名覆蓋內建函數的變量。和str()以及.. – monkut