Search code examples
pythonpython-3.xdeque

pythonic way to pop elements out of stack (collections.deque)


TL;DR: see code at the bottom.

I'm implementing a Reverse Polish Notation calculator in Python, using the collections.deque stack implementation.

Since I'm handling also the case of functions with multiple arguments, I use a separator symbol that I place before the actual arguments. For example, given the following expression as input: max(2, 3, 4), the Shunting Yard algorithm produces the following iterable: ['|', '2', '3', '4', 'max'].

When I iterate over it, the separator and the numbers are pushed onto a stack; if a function is encountered, all the previous elements up to the separator are "popped" out of the stack and appended into a list.

Is there a more pythonic way to pop out elements from the end of a stack up to a certain condition? My code so far:

args = []
while op_stack[-1] != FUNC_ARGS_SEPARATOR:
    args.append(op_stack.pop())

Solution

  • With the help of a friend we ended up the iter keyword with sep as sentinel:

    from collections import deque
    
    sep = "|"
    op_stack = deque([sep, 2, 3, 4])
    
    args = iter(op_stack.pop, sep)
    
    print(list(args))
    

    which should be one of the most pythonic and KISS way to solve this, so I'm going to accept this as the answer.

    Thanks for the help folks!