Skip to content
Snippets Groups Projects
rpn.py 667 B
Newer Older
  • Learn to ignore specific revisions
  • 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)
    
    ehcole's avatar
    ehcole committed
        if len(stack) > 1:
            raise ValueError("too many arguments on the stack")
    
    ehcole's avatar
    ehcole committed
        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()