Skip to content

Instantly share code, notes, and snippets.

@vastus
Created March 25, 2016 14:12
Show Gist options
  • Select an option

  • Save vastus/192bdfcd794e744495f4 to your computer and use it in GitHub Desktop.

Select an option

Save vastus/192bdfcd794e744495f4 to your computer and use it in GitHub Desktop.
grammar = [
("exp", ["exp", "+", "exp"]),
("exp", ["exp", "-", "exp"]),
("exp", ["(", "exp", ")"]),
("exp", ["num"]),
]
def expand(tokens, grammar):
for pos in range(len(tokens)):
for rule in grammar:
if tokens[pos] == rule[0]:
yield tokens[0:pos] + rule[1] + tokens[pos+1:]
depth = 1
utterances = [["a", "exp"]]
for x in range(depth):
for sentence in utterances:
utterances = utterances + \
[x for x in expand(sentence, grammar)]
for sentence in utterances:
print(sentence)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment