Skip to content

Instantly share code, notes, and snippets.

@theptrk
Created January 25, 2022 04:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/5ee1d0f65683122cb17c269f5e0cb470 to your computer and use it in GitHub Desktop.
Save theptrk/5ee1d0f65683122cb17c269f5e0cb470 to your computer and use it in GitHub Desktop.
import random
def is_terminal(token):
return token[0] != "_"
def expand(grammer, tokens):
result = []
for token in tokens:
if is_terminal(token):
result.append(token)
else:
replacement = grammer[token]
if is_terminal(replacement[0]):
return [random.choice(replacement)]
else:
for replace in replacement:
result = result + expand(grammer, [replace])
return result
def generate_sentence(grammer):
return expand(grammer, ["_S"])
generate_sentence({
"_S": ["_A", "_N", "_V", "_N_thing"],
"_A": ["big", "scary", "blue", "surprising"],
"_N": ["cat", "dog", "bear"],
"_N_thing": ["a hot dog", "a trash can", "all the snacks"],
"_V": ["ate", "devoured", "ran"],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment