我用這個可怕而低效的實現來找到可以刪除最後連續的最後一個字母並且仍然是單詞的單詞。例如,Rodeo是一個衆所周知的:Rodeo,Rode,Rod,Ro。 該程序發現'作曲家':作曲家,作曲家,撰寫,作曲,對比Python-什麼單詞可以刪除最連續的字母,仍然是字典有效的單詞?
我想知道如何創建一個程序,找到最長的單詞, )移除,它仍然被認爲是一個字:
例如:野獸,最好的賭注,是 - 將是一個有效的可能性
這裏是我的我的程序,以找到一個去除連續的字母(」 m也有興趣聽聽如何改進和優化):
#Recursive function that finds how many letters can be removed from a word and
#it still be valid.
def wordCheck(word, wordList, counter):
if len(word)>=1:
if word in wordList:
return (wordCheck(word[0:counter-1], wordList, counter-1))
else:
return counter
return counter
def main():
a = open('C:\\Python32\\megalist2.txt', 'r+')
wordList = set([line.strip() for line in a])
#megaList contains a sorted list of tuple of
#(the word, how many letters can be removed consecutively)
megaList = sorted([(i, len(i)-1- wordCheck(i, wordList, len(i))) for i in wordList], key= lambda megaList: megaList[1])
for i in megaList:
if i[1] > 3:
print (i)
if __name__ == '__main__':
main()
請注意['r +'也打開了_writing_]的文件(http://docs.python.org/library/functions.html#open)。除非你的程序實際上會修改你的字典,否則我建議將'open'模式改爲'r'。 – sarnold 2011-05-21 22:23:00
對於你原來的問題,你可以從所有字典中生成一種特殊的[基數樹](http://en.wikipedia.org/wiki/Radix_tree),最長的單詞是這棵樹中最長的路徑。 – 2011-05-21 22:29:16
最近有人問到一個非常類似的問題,因此可能值得嘗試幾個搜索。這通常與anagrams的特殊情況有關,並且http://stackoverflow.com/questions/880559/algorithm-to-get-a-list-of-all-words-that-are-anagrams-of-all-substrings scrabbl可能是一個好的開始。 – 2011-05-21 22:32:02