Skip to content
Snippets Groups Projects
rpn.py 584 B
Newer Older
ehcole's avatar
ehcole committed
#!/usr/bin/env python3

ehcole's avatar
ehcole committed
def calculate(arg):
    stack = []
    tokens = arg.split(" ")
    for token in tokens:
        try:
            stack.append(int(token))
        except ValueError:
            val2 = stack.pop()
ehcole's avatar
ehcole committed
            val1 = stack.pop()
ehcole's avatar
ehcole committed
            if token == '+':
                result = val1 + val2
            elif token == '-':
ehcole's avatar
ehcole committed
                result = val1 - val2
ehcole's avatar
ehcole committed
            stack.append(result)
    return stack[0]
    
            
    
ehcole's avatar
ehcole committed
def main():
    while True:
ehcole's avatar
ehcole committed
        print(calculate(input("rpn calc> ")))
        
ehcole's avatar
ehcole committed

if __name__ == '__main__':
    main()