Browse Source

Initial code commit

Johann Schmitz 2 years ago
parent
commit
e2a4de434d
Signed by: Johann Schmitz <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/
67 67
 
68 68
 # PyCharm
69 69
 .idea
70
+
71
+src/test.py

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

@@ -0,0 +1,37 @@
1
+# -*- coding: utf-8 -*-
2
+from __future__ import division
3
+import operator
4
+
5
+OPERATORS = {
6
+	'+': operator.add,
7
+	'-': operator.sub,
8
+	'*': operator.mul,
9
+	'/': lambda a, b: a / b,
10
+	'^': operator.pow,
11
+}
12
+
13
+
14
+class RPN(object):
15
+
16
+	def calc(self, expression, vars=None):
17
+		vars = vars or {}
18
+		tokens = []
19
+
20
+		for x in expression if isinstance(expression, (list, tuple)) else expression.strip().split():
21
+			if x in vars:
22
+				tokens.append(vars[x])
23
+			elif x in OPERATORS:
24
+				tokens.append(x)
25
+			else:
26
+				tokens.append(float(x) if '.' in x or 'e' in x.lower() else int(x))
27
+
28
+		while len(tokens) > 1:
29
+			print("Current token list: %s" % tokens)
30
+			for i, token in enumerate(tokens):
31
+				if token in OPERATORS:
32
+					assert i >= 2
33
+
34
+					tokens[i-2:i+1] = [OPERATORS[token](tokens[i-2], tokens[i-1])]
35
+					break
36
+
37
+		return tokens[0]

+ 14
- 0
tests/test_simple_math.py View File

@@ -0,0 +1,14 @@
1
+# -*- coding: utf-8 -*-
2
+from rpn import RPN
3
+
4
+
5
+class TestSimpleMath(object):
6
+
7
+	def test_basic_operators(self):
8
+		for exp, result in [
9
+			('1 2 +', 3),
10
+			('1 2 -', -1),
11
+			('1 2 *', 2),
12
+			('1 2 /', 0.5)
13
+		]:
14
+			assert RPN().calc(exp) == result