Skip to content

Instantly share code, notes, and snippets.

@mao-odoo
Last active March 22, 2021 09:01
Show Gist options
  • Save mao-odoo/c4a568c861e9037e2afee9a76a7d70da to your computer and use it in GitHub Desktop.
Save mao-odoo/c4a568c861e9037e2afee9a76a7d70da to your computer and use it in GitHub Desktop.
python rpn with support for unary and ternary operator (+ ready for more )
import inspect
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"x": lambda a, b: a * b,
"/": lambda a, b: a / b,
"sqrt": lambda a: a ** 0.5,
"ternary_operator": lambda a, b, c: a + b + c + 1,
}
ops = {
token: (func, len(inspect.getfullargspec(func).args))
for token, func in ops.items()
}
# first element of tuple is the function to execute
# second is the number of operators it consumes
def rpn(entry):
def pop_elements(stack, x):
return [stack.pop() for i in range(x)][::-1]
stack = []
try:
for token in entry.split():
# print(stack)
if token in ops:
nums = pop_elements(stack, ops[token][1])
z = ops[token][0](*nums)
stack.append(z)
else:
# should be an number
stack.append(float(token))
assert len(stack) == 1
except (IndexError, AssertionError):
print("Malformed operation")
except ValueError:
print("this only supports numbers")
else:
return stack[0]
if __name__ == '__main__':
rpn("1.44 2 / 3.2 x 5 - sqrt")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment