【发布时间】:2018-12-16 03:05:26
【问题描述】:
我正在尝试将“alice_list”中的单词与“dictionary_list”进行比较,如果在“dictionary_list”中找不到单词,则打印它并说它可能拼写错误。我遇到的问题是如果找不到它就不会打印任何东西,也许你们可以帮助我。我将“alice_list”附加到大写字母,因为“dictionary_list”全部大写。任何有关它为什么不起作用的帮助将不胜感激,因为我即将把头发拉出来!
import re
# This function takes in a line of text and returns
# a list of words in the line.
def split_line(line):
return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line)
# --- Read in a file from disk and put it in an array.
dictionary_list = []
alice_list = []
misspelled_words = []
for line in open("dictionary.txt"):
line = line.strip()
dictionary_list.extend(split_line(line))
for line in open("AliceInWonderLand200.txt"):
line = line.strip()
alice_list.extend(split_line(line.upper()))
def searching(word, wordList):
first = 0
last = len(wordList) - 1
found = False
while first <= last and not found:
middle = (first + last)//2
if wordList[middle] == word:
found = True
else:
if word < wordList[middle]:
last = middle - 1
else:
first = middle + 1
return found
for word in alice_list:
searching(word, dictionary_list)
--------- 已编辑的有效代码 ---------- 如果有人遇到同样的问题,请更新一些内容,并使用“for word not in”来仔细检查搜索中输出的内容。
"""-----Binary Search-----"""
# search for word, if the word is searched higher than list length, print
words = alice_list
for word in alice_list:
first = 0
last = len(dictionary_list) - 1
found = False
while first <= last and not found:
middle = (first + last) // 2
if dictionary_list[middle] == word:
found = True
else:
if word < dictionary_list[middle]:
last = middle - 1
else:
first = middle + 1
if word > dictionary_list[last]:
print("NEW:", word)
# checking to make sure words match
for word in alice_list:
if word not in dictionary_list:
print(word)
【问题讨论】:
标签: python algorithm search binary-search