我試圖讓一個字謎算法,但我卡住了一次,我到了遞歸部分。讓我知道是否需要更多信息。Python - 遞歸單詞列表
我的代碼:
def ana_words(words, letter_count):
"""Return all the anagrams using the given letters and allowed words.
- letter_count has 26 keys (one per lowercase letter),
and each value is a non-negative integer.
@type words: list[str]
@type letter_count: dict[str, int]
@rtype: list[str]
"""
anagrams_list = []
if not letter_count:
return [""]
for word in words:
if not _within_letter_count(word, letter_count):
continue
new_letter_count = dict(letter_count)
for char in word:
new_letter_count[char] -= 1
# recursive function
var1 = ana_words(words[1:], new_letter_count)
sorted_word = ''.join(word)
for i in var1:
sorted_word = ''.join([word, i])
anagrams_list.append(sorted_word)
return anagrams_list
詞是從一個文件中的單詞列表,字母數是一個字符(小寫的話)的字典。單詞中的單詞列表也已經小寫。
輸入:打印ana_words( '宿舍')
輸出我得到:我想
['dirtyroom', 'dotoi', 'doori', 'dormitory', 'drytoori', 'itorod', 'ortoidry', 'rodtoi', 'roomidry', 'rootidry', 'torodi']
輸出:
['dirty room', 'dormitory', 'room dirty']
鏈接字列表:https://1drv.ms/t/s!AlfWKzBlwHQKbPj9P_pyKdmPwpg
是否需要(或意志)編寫遞歸的東西?因爲它對你的目標確實是違反直覺的。 –
@Rightleg我想用遞歸來做,因爲我正在學習遞歸。 – Theo
'打印字謎('宿舍')'如何知道'髒,宿舍,房間'? –