Skip to content

Instantly share code, notes, and snippets.

@nathan-heskia
Last active January 19, 2018 07:53
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 nathan-heskia/c58f92cce94f8127c717270c11243b71 to your computer and use it in GitHub Desktop.
Save nathan-heskia/c58f92cce94f8127c717270c11243b71 to your computer and use it in GitHub Desktop.
Create an interpreter for the grammar "expression := integer | ( function expression expression )"
# Something I got too nervous doing in an interview
import re
def evalexpr(expr):
name, operands = expr[0], map(lambda x : int(x), expr[1:])
if name == 'add':
return reduce(lambda x, y : x + y, operands, 0)
elif name == 'mul':
return reduce(lambda x, y : x * y, operands, 1)
def parse(l):
m = re.search('\((.*)\)', l)
s = []
while m is not None:
s.append(m.group(1))
m = re.search('\((.*)\)', m.group(1))
s.reverse()
if len(s) < 1:
return l
prev = s[0]
result = evalexpr(prev.strip().split(' '))
for i in xrange(1, len(s)):
x = re.sub(r'\(|\)', '', s[i].replace(prev, str(result)))
result = evalexpr(x.strip().split(' '))
prev = s[i]
return result
if __name__ == '__main__':
expression = '( mul ( add 1 ( add ( mul ( add 1 ( mul ( add 3 4 ) 7 ) ) 2 ) 3 ) ) 5 6 )'
print parse(expression)
expression = '( add 2 2 )'
print parse(expression)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment