Skip to content

Instantly share code, notes, and snippets.

@ptmcg
Last active May 19, 2022 21:36
Show Gist options
  • Save ptmcg/c5dab31d2590212ac2aa357105359849 to your computer and use it in GitHub Desktop.
Save ptmcg/c5dab31d2590212ac2aa357105359849 to your computer and use it in GitHub Desktop.
PyScript demo of a pyparsing arithmetic parser/evaluator
<html>
<head>
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<table cellpadding=30 border=2>
<tr>
<td>
<pre>
# Parse an arithmetic expression into elements according
# to standard operator precedence rules.
import pyparsing as pp
integer = pp.common.integer
arith_expr = pp.infix_notation(integer,
[
('-', 1, pp.OpAssoc.RIGHT),
(pp.one_of('* /'), 2, pp.OpAssoc.LEFT),
(pp.one_of('+ -'), 2, pp.OpAssoc.LEFT),
])
# try it out!
arith = "10*3+4/2"
print(arith_expr.parse_string(arith).as_list())
============================
<py-script>
import pyparsing as pp
integer = pp.common.integer
arith_expr = pp.infix_notation(integer,
[
('-', 1, pp.OpAssoc.RIGHT),
(pp.one_of('* /'), 2, pp.OpAssoc.LEFT),
(pp.one_of('+ -'), 2, pp.OpAssoc.LEFT),
])
# try it out!
arith = "10*3+4/2"
print(arith_expr.parse_string(arith).as_list())
</py-script>
</pre>
</td>
</tr>
<tr>
<td>
<pre>
# Parse and evaluate an arithmetic expression according
# to standard operator precedence rules.
import operator
import pyparsing as pp
integer = pp.common.integer
# add parse actions to evaluate the arithmetic expression
def eval_unary_minus(t):
t, = t
return -(t[1])
def eval_binary(t):
op_map = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
t, = t
ret = t[0]
for op, operand in zip(t[1::2], t[2::2]):
ret = op_map[op](ret, operand)
return ret
eval_expr = pp.infix_notation(integer,
[
('-', 1, pp.OpAssoc.RIGHT, eval_unary_minus),
(pp.one_of('* /'), 2, pp.OpAssoc.LEFT, eval_binary),
(pp.one_of('+ -'), 2, pp.OpAssoc.LEFT, eval_binary),
])
# try it out!
arith = "10*3+4/2"
print(eval_expr.parse_string(arith)[0])
============================
<py-script>
import operator
# add parse actions to evaluate the arithmetic expression
def eval_unary_minus(t):
t, = t
return -(t[1])
def eval_binary(t):
op_map = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
t, = t
ret = t[0]
for op, operand in zip(t[1::2], t[2::2]):
ret = op_map[op](ret, operand)
return ret
eval_expr = pp.infix_notation(integer,
[
('-', 1, pp.OpAssoc.RIGHT, eval_unary_minus),
(pp.one_of('* /'), 2, pp.OpAssoc.LEFT, eval_binary),
(pp.one_of('+ -'), 2, pp.OpAssoc.LEFT, eval_binary),
])
# try it out!
arith = "10*3+4/2"
print(eval_expr.parse_string(arith)[0])
</py-script>
</pre>
</td>
</tr>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment