Skip to content

Instantly share code, notes, and snippets.

@erikrose
Created November 5, 2012 19:18
Show Gist options
  • Save erikrose/4019721 to your computer and use it in GitHub Desktop.
Save erikrose/4019721 to your computer and use it in GitHub Desktop.
RPN iterator
from collections import deque
from more_itertools import consumer
OPS = {'+': lambda a, b: b + a,
'/': lambda a, b: b / a,
'-': lambda a, b: b - a,
'*': lambda a, b: b * a}
@consumer
def eval_rpn():
"""A consumer iterator that takes pieces of an RPN expression and yields
the evaluated stack"""
stack = []
while True:
i = yield stack
op = OPS.get(i)
stack.append(op(stack.pop(), stack.pop()) if op else i)
INPUT = [5, 15, '+', 4, '/']
rpn = eval_rpn()
stacks = (rpn.send(i) for i in INPUT)
# I think I'll add a last() to more_itertools so we don't have to do this less readable thing:
print deque(stacks, 1).pop()[0]
@erikrose
Copy link
Author

erikrose commented Nov 5, 2012

And without the hotdogging:

OPS = {'+': lambda a, b: b + a,
       '/': lambda a, b: b / a,
       '-': lambda a, b: b - a,
       '*': lambda a, b: b * a}


def eval_rpn(input):
    """A consumer iterator that takes pieces of an RPN expression and yields
    the evaluated stack"""
    stack = []
    for i in input:
        op = OPS.get(i)
        stack.append(op(stack.pop(), stack.pop()) if op else i)
    return stack[0]


print eval_rpn([5, 15, '+', 4, '/'])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment