Created
February 24, 2019 14:49
-
-
Save inesusvet/ad31e071d18a6ac73347c36fefa8f99a to your computer and use it in GitHub Desktop.
Coding dojo in Minsk session result for 2019-02-24
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
""" | |
See https://www.codewars.com/kata/reverse-polish-notation-calculator | |
Your job is to create a calculator which evaluates expressions in Reverse Polish notation. | |
For example expression 5 1 2 + 4 * + 3 - (which is equivalent to 5 + ((1 + 2) * 4) - 3 in normal notation) | |
should evaluate to 14. | |
For your convenience, the input is formatted such that a space is provided between every token. | |
Empty expression should evaluate to 0. | |
Valid operations are +, -, *, /. | |
You may assume that there won't be exceptional situations (like stack underflow or division by zero). | |
""" | |
def numeric(text): | |
if text.isdigit(): | |
return int(text) | |
return float(text) | |
def operation(op, a, b): | |
if op == '+': | |
return a + b | |
elif op == '-': | |
return a - b | |
elif op == '*': | |
return a * b | |
elif op == '/': | |
return a / b | |
def calc(expr): | |
""" | |
>>> calc("") | |
0 | |
>>> calc("3") | |
3 | |
>>> calc("3.5") | |
3.5 | |
>>> calc("1 3 +") | |
4 | |
>>> calc("1 3 *") | |
3 | |
>>> calc("1 3 -") | |
-2 | |
>>> calc("4 2 /") | |
2 | |
>>> calc("5 1 2 + 4 * + 3 -") | |
14 | |
""" | |
if expr == '': | |
return 0 | |
tokens = expr.split() | |
# return solve(tokens[::-1]) | |
stack = [] | |
for token in tokens: | |
if token in '+-*/': | |
b = stack.pop() | |
a = stack.pop() | |
result = operation(token, a, b) | |
stack.append(result) | |
else: | |
stack.append(numeric(token)) | |
return stack.pop() | |
def solve(tokens): | |
"""Try recursion approach. Not finised""" | |
if not tokens: | |
return 0 | |
op = tokens.pop(0) | |
if op not in '+-*/': | |
return numeric(op) | |
b = tokens.pop(0) | |
if b in '+-*/': | |
tokens.append(b) | |
b = solve(tokens) | |
a = tokens.pop(0) | |
if a in '+-*/': | |
tokens.append(a) | |
a = solve(tokens) | |
a = numeric(a) | |
b = numeric(b) | |
return operation(op, a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment