Created
March 12, 2015 11:09
-
-
Save mdamien/024891c770e3071dbefc to your computer and use it in GitHub Desktop.
Formal grammar interpreter
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
#Execute a type 3 grammar | |
rules2 = """ | |
S -> ATC | |
A -> aA | | |
C -> cC | | |
T -> abT | ab | |
""" | |
class bcolors: | |
HEADER = '\033[95m' | |
OKBLUE = '\033[94m' | |
OKGREEN = '\033[92m' | |
WARNING = '\033[93m' | |
FAIL = '\033[91m' | |
ENDC = '\033[0m' | |
BOLD = '\033[1m' | |
UNDERLINE = '\033[4m' | |
def print_colored(text, color): | |
print(color, text, bcolors.ENDC) | |
def parse_rules(text): | |
rules = {} | |
for line in text.split('\n'): | |
if line.strip(): | |
symb, choices = line.split('->') | |
rules[symb.strip()] = \ | |
[x.strip() for x in choices.strip().split('|')] | |
return rules | |
def apply_rules(s, rules, limit=5): | |
terminal = True | |
for x in s: | |
if x in rules: | |
terminal = False | |
break | |
if terminal: | |
print_colored(s, bcolors.OKGREEN) | |
else: | |
print_colored(s, bcolors.OKBLUE) | |
if limit == 0: | |
return | |
for i,x in enumerate(s): | |
if x in rules: | |
for y in rules[x]: | |
t = list(s) | |
t[i] = y | |
new_s = ''.join(t) | |
apply_rules(new_s, rules, limit=limit-1) | |
rules = parse_rules(rules2) | |
print(rules) | |
apply_rules ('S', rules) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment