import random # # Generating random strings from a context-free grammar. # def noun(): return random.choice(['idea', 'bagel', 'milk', 'cow']) def verb(): return random.choice(['sleeps', 'eats', 'swims', 'sprints']) def article(): return random.choice(['the', 'a']) def adjective(): return random.choice(['colorless','green','smelly']) def adverb(): return random.choice(['furiously','soothingly','intentionally']) def pre_noun_phrase(): return random.choice([[noun],[adjective, pre_noun_phrase]]) def noun_phrase(): return [article, pre_noun_phrase] def verb_phrase(): return random.choice([[verb],[verb, adverb]]) def sentence(): return [noun_phrase, verb_phrase] def process(cfg): if isinstance(cfg, str): return cfg else: # we know it's an instance of a list of functions result = "" for item in cfg: result += process(item()) + " " return result.strip()