我试图让一个字谜算法,但我卡住了一次,我到了递归部分。让我知道是否需要更多信息。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
'打印字谜('宿舍')'如何知道'脏,宿舍,房间'? –