Last active
October 15, 2015 14:38
-
-
Save javi830810/a0ada227aca8a31be213 to your computer and use it in GitHub Desktop.
Polish notation
This file contains hidden or 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
| class Stack(object): | |
| def __init__(self): | |
| self.stack = [] | |
| def push(self, elem): | |
| self.stack.append(elem) | |
| def peek(self): | |
| if not self.stack: | |
| return None | |
| return self.stack[len(self.stack) - 1] | |
| def pop(self): | |
| if not self.stack: | |
| return None | |
| elem = self.stack[len(self.stack) - 1] | |
| del self.stack[len(self.stack)-1] | |
| return elem | |
| def generator(self): | |
| x = self.pop() | |
| if x: | |
| yield x | |
| def is_op(op): | |
| return op == '+' or op == '-' or op == '/' or op == '*' | |
| def solve_op(num1,num2,op): | |
| if op == '+': | |
| return int(num1) + int(num2) | |
| elif op == '-': | |
| return int(num1) - int(num2) | |
| elif op == '*': | |
| return int(num1) * int(num2) | |
| elif op == '/': | |
| return int(num1) / int(num2) | |
| def polish_notation(str): | |
| stack = Stack() | |
| stack_2 = Stack() | |
| for x in str.strip().split(' ')[::-1]: | |
| stack.push(x) | |
| while stack.peek(): | |
| elem = stack.pop() | |
| if not is_op(elem): | |
| stack_2.push(elem) | |
| else: | |
| stack_2.push(solve_op(stack_2.pop(), stack_2.pop(), elem)) | |
| return stack_2.pop() | |
| print polish_notation("2 4 1 + *") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment