-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfabula.py
94 lines (83 loc) · 3.02 KB
/
fabula.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import math
from math import pi
from math import e
import re
def postfix_calc(seq: list):
stack = []
for i in range(len(seq)):
if (re.search(r'\d+|-\d+', seq[i]) is not None) and (re.search(r'[\d]+\.', seq[i]) is None):
stack.append(int(seq[i]))
elif re.search(r'[0-9]+\.[0-9]+|-[0-9]+\.[0-9]+', seq[i]) is not None:
stack.append(float(seq[i]))
elif re.search(r'\bpi\b', seq[i]) is not None:
stack.append(pi)
elif re.search(r'\be\b', seq[i]) is not None:
stack.append(e)
elif seq[i] == '+':
y = stack.pop()
x = stack.pop()
z = x + y
stack.append(z)
elif seq[i] == '-':
y = stack.pop()
x = stack.pop()
z = x - y
stack.append(z)
elif seq[i] == '*':
y = stack.pop()
x = stack.pop()
z = x * y
stack.append(z)
elif seq[i] == '/':
y = stack.pop()
x = stack.pop()
z = (float(x) / float(y))
stack.append(z)
elif seq[i] == '**':
y = stack.pop()
x = stack.pop()
z = x ** y
stack.append(z)
result = stack.pop()
return result
def to_int(seq):
try:
number = int(seq)
return number
except ValueError:
pass
def to_float(seq):
try:
number = float(seq)
return number
except ValueError:
pass
def tokenizer(seq):
return list(filter(lambda s: s.isdigit() or (re.search(r'\bpi\b', s)) or (re.search(r'\be\b', s)) or s == '**' or s == '-' or s == '+' or s == '*' or s == '/' or to_float(s) or to_int(s), seq.split(' ')))
def shell():
print('####################################')
print('# FABULA #')
print('# A little postfix calculator #')
print('# #')
print('# Type whereami if you need help #')
print('####################################')
while True:
sequence = input('>>> ')
if sequence == 'whereami':
print('|-----------### HELP ###-----------')
print('| Operators: + , - , * , / , **')
print('| Mathematical constants: pi , e')
print('|---------### EXAMPLES ###---------')
print('| >>> 2 9 * pi +')
print('| <<< [\'2\', \'9\', \'*\', \'pi\', \'+\']')
print('| <<< 21.141592653589793')
print('|__________________________________')
elif sequence == 'exit':
exit()
else:
print('<<<', tokenizer(sequence))
try:
print('<<<', postfix_calc(tokenizer(sequence)))
except:
print('<<< [Unknown sequence]')
shell()