因此,创建一定长度的所有可能的话,让我们说我们有一本字典蟒蛇递归:使用文字的键值字典
>>> dictionary
{'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']}
我们希望创造一定长度的所有可能的句子(比如5我们的案例),其中每个句子在字典中以key
开头,后面跟着一个元素的值,然后所选值成为下一步的键(如果该值也在键集中)等等,直到我们点击所需的句子长度。
要详细,比方说,在句子中的一个(表示s
)我们生产我们的第一个关键是and
,那么它会因为(and,the)
跟着the
是键值对。所以,现在我们有s = "and the"
。同时延长s
,现在我们将使用the
的关键。我们有两个可能的值the
是cat
和dog
。所以,从s
,我们有 s1 = "and the cat"
和s2 = "and the dog"
。现在,dog
是不是在字典中key
,所以我们不能再追求这条道路实现长度为5左右的句子,我们停在这里。但是,我们可以通过它延伸到s1 = "and the cat and"
等持续s1
......
对于给定的字典,我们应该得到下面的句子:
'and the cat and the',
'the cat and the dog',
'the cat and the cat',
'cat and the cat and'
我与递归回溯试图像以下:
dictionary = {'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']}
sentence_list = []
sentence_length = 5
def recurse(split_sentence,key):
if len(split_sentence) >= sentence_length:
sentence_list.append(split_sentence)
return
elif key not in dictionary.keys():
return
else:
for value in dictionary[key]:
split = split_sentence
split.append(value)
recurse(split,value)
return
for key in dictionary.keys():
split_sentence = []
recurse(split_sentence, key)
for elem in sentence_list:
sentence = " ".join(elem)
print sentence + "\n"
但它给我的输出
the cat and the cat dog dog
the cat and the cat dog dog
the cat and the cat dog dog
cat and the cat and dog dog
cat and the cat and dog dog
cat and the cat and dog dog
and the cat and the dog
and the cat and the dog
有人能帮我弄清楚我做错了什么吗?