Browse Source

Initial code commit

master
Johann Schmitz 4 years ago
parent
commit
e2a4de434d
Signed by: ercpe <johann@j-schmitz.net> GPG Key ID: A084064277C501ED
3 changed files with 53 additions and 0 deletions
  1. +2
    -0
      .gitignore
  2. +37
    -0
      src/rpn/__init__.py
  3. +14
    -0
      tests/test_simple_math.py

+ 2
- 0
.gitignore View File

@@ -67,3 +67,5 @@ target/

# PyCharm
.idea

src/test.py

+ 37
- 0
src/rpn/__init__.py View File

@@ -0,0 +1,37 @@
# -*- coding: utf-8 -*-
from __future__ import division
import operator

OPERATORS = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': lambda a, b: a / b,
'^': operator.pow,
}


class RPN(object):

def calc(self, expression, vars=None):
vars = vars or {}
tokens = []

for x in expression if isinstance(expression, (list, tuple)) else expression.strip().split():
if x in vars:
tokens.append(vars[x])
elif x in OPERATORS:
tokens.append(x)
else:
tokens.append(float(x) if '.' in x or 'e' in x.lower() else int(x))

while len(tokens) > 1:
print("Current token list: %s" % tokens)
for i, token in enumerate(tokens):
if token in OPERATORS:
assert i >= 2

tokens[i-2:i+1] = [OPERATORS[token](tokens[i-2], tokens[i-1])]
break

return tokens[0]

+ 14
- 0
tests/test_simple_math.py View File

@@ -0,0 +1,14 @@
# -*- coding: utf-8 -*-
from rpn import RPN


class TestSimpleMath(object):

def test_basic_operators(self):
for exp, result in [
('1 2 +', 3),
('1 2 -', -1),
('1 2 *', 2),
('1 2 /', 0.5)
]:
assert RPN().calc(exp) == result

Loading…
Cancel
Save