のキーと値の辞書を使用して、特定の長さのすべての可能な文を作成し、(5を言うのは、我々は我々が一定の長さのすべての可能な文章を作成したい辞書Pythonの再帰:だから言葉
>>> dictionary
{'and': ['the'], 'the': ['cat', 'dog'], 'cat': ['and']}
を持っているとしましょう私たちの場合)、各文はディクショナリのkey
で始まり、その値の要素が続き、次に選択された値が次のステップのキーになります(値がキーのセットに含まれている場合)。所望の文章の長さ。 (s
を表す)我々は最初のキーを生産している文章の一つに、たとえば、手の込んだ
は(and,the)
は、キーと値のペアであるので、それはthe
が続く、and
です。だから今はs = "and the"
です。 s
を拡張している間、今度はthe
をキーとして使用します。 the
には、cat
とdog
の2つの値があります。したがって、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
を与えています
誰かが私が間違っているところを見つけ出す手助けをしてくれますか?