'Building a list of possible sentences with variable words in Python?
I want to get a list of all sentence possibilities by combining sentence a list of possible sentence structures with possible variables.
sentenceStructures = [
"What [x] is [y]",
"What [y] is [x]"
]
variables = {
"[x]": ["a", "b", "c"],
"[y]":["q", "r", "s"]
}
The final answer should be
allPossibleSentences = [
"What a is q",
"What b is q",
"What c is q",
"What a is r",
"What b is r",
"What c is r",
"What a is s",
"What b is s",
"What c is s",
"What q is a",
"What r is a",
"What s is a",
"What q is b",
"What r is b",
"What s is b",
"What q is c",
"What r is c",
"What s is c"
]
I figure I should use recursion to get a list of all possibilities.
allPossibleSentences = []
def fillVariable(sentence):
sentence.find("[")
#this is where i'm stuck, i'm not sure how to start the recursion
allPossibleSentences.append(possibility)
for sentence in sentenceStructures:
fillVariables(sentence)
Any help or pointers appreciated?
Solution 1:[1]
You can use nested for loop. You don't need recursion. Something along the line of
sentenceStructures = [
"What [x] is [y]",
"What [y] is [x]"
]
variables = {
"[x]": ["a", "b", "c"],
"[y]":["q", "r", "s"]
}
x = variables["[x]"]
y = variables["[y]"]
answer = []
for sentence in sentenceStructures:
for x_item in x:
for y_item in y:
s = sentence.replace("[x]", x_item).replace("[y]", y_item)
answer.append(s)
print(answer)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tejas Parnerkar |
