Created
November 5, 2012 19:18
-
-
Save erikrose/4019721 to your computer and use it in GitHub Desktop.
RPN iterator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And without the hotdogging: