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)