Skip to content

Instantly share code, notes, and snippets.

@Beneboe
Created August 19, 2020 14:44
Show Gist options
  • Save Beneboe/021f08ce731d6f637c8d1505379d65d7 to your computer and use it in GitHub Desktop.
Save Beneboe/021f08ce731d6f637c8d1505379d65d7 to your computer and use it in GitHub Desktop.
Bracket Parser
# expression := term operator term
# term := literal
# term := "(" expression ")"
# 0 - bracket open
# 1 - bracket close
# 2 - number
# 3 - operator
tokens = [
{"type": 0},
{"type": 2, "value": 10 ** 1},
{"type": 3},
{"type": 2, "value": 10 ** 2},
{"type": 1},
{"type": 3},
{"type": 0},
{"type": 0},
{"type": 2, "value": 10 ** 4},
{"type": 3},
{"type": 2, "value": 10 ** 5},
{"type": 1},
{"type": 3},
{"type": 2, "value": 10 ** 7},
{"type": 1}
]
def cons(tokens):
pos = 0
start = pos
term1 = None
if tokens[pos]["type"] == 0:
count = 1
while count > 0:
pos += 1
if tokens[pos]["type"] == 0:
count += 1
elif tokens[pos]["type"] == 1:
count -= 1
term1 = cons(tokens[(start + 1):pos])
elif tokens[pos]["type"] == 2:
term1 = tokens[pos]["value"]
else:
print("syntax error")
return
pos += 1
if tokens[pos]["type"] != 3:
print("syntax error")
return
pos += 1
start = pos
term2 = None
if tokens[pos]["type"] == 0:
count = 1
while count > 0:
pos += 1
if tokens[pos]["type"] == 0:
count += 1
elif tokens[pos]["type"] == 1:
count -= 1
term2 = cons(tokens[(start + 1):pos])
elif tokens[pos]["type"] == 2:
term2 = tokens[pos]["value"]
else:
print("syntax error")
return
return term1 + term2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment