Created
January 25, 2022 04:45
-
-
Save theptrk/5ee1d0f65683122cb17c269f5e0cb470 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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