0

因此,创建一定长度的所有可能的话,让我们说我们有一本字典蟒蛇递归:使用文字的键值字典

>>> dictionary 
{'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']} 

我们希望创造一定长度的所有可能的句子(比如5我们的案例),其中每个句子在字典中以key开头,后面跟着一个元素的值,然后所选值成为下一步的键(如果该值也在键集中)等等,直到我们点击所需的句子长度。

要详细,比方说,在句子中的一个(表示s)我们生产我们的第一个关键是and,那么它会因为(and,the)跟着the是键值对。所以,现在我们有s = "and the"。同时延长s,现在我们将使用the的关键。我们有两个可能的值thecatdog。所以,从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 

有人能帮我弄清楚我做错了什么吗?

回答

1

的问题是,要修改在周围递归调用你的循环split_sentence;将它分配给另一个变量只意味着你有一个新的名称为同一个列表。创建一个新的列表以进行递归调用可以这样完成:

for value in dictionary[key]: 
     recurse(split_sentence+[value],value)