-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_calculator.py
88 lines (77 loc) · 2.54 KB
/
basic_calculator.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
import math
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self):
self.stack = None
def is_empty(self):
return self.stack is None
def push(self, value):
old = self.stack
self.stack = Node(value, old)
def pop(self):
if not self.is_empty():
value = self.stack.value
self.stack = self.stack.next
return value
return None
def top(self):
if not self.is_empty():
return self.stack.value
return None
def calculate(s: str) -> int:
numbers_stack = Stack()
operators_stack = Stack()
number_string = ""
negative = False
evaluate_next = False
for character in s:
if character.isdigit():
number_string += character
else:
if number_string:
if negative:
numbers_stack.push(-int(number_string))
negative = False
else:
numbers_stack.push(int(number_string))
number_string = ""
if evaluate_next:
second = numbers_stack.pop()
first = numbers_stack.pop()
evaluate_next = False
operator = operators_stack.pop()
if operator == '*':
numbers_stack.push(first * second)
elif operator == '/':
numbers_stack.push(math.trunc(first /second))
if character == '-':
negative = True
operators_stack.push('+')
elif character in ['*', '/']:
operators_stack.push(character)
evaluate_next = True
elif operator == '+':
operators_stack.push(character)
if number_string:
if negative:
numbers_stack.push(-int(number_string))
negative = False
else:
numbers_stack.push(int(number_string))
while not operators_stack.is_empty():
operator = operators_stack.pop()
second = numbers_stack.pop()
first = numbers_stack.pop()
if operator == '+':
numbers_stack.push(first + second)
elif operator == '*':
numbers_stack.push(first * second)
elif operator == '/':
numbers_stack.push(math.trunc(first/second))
return numbers_stack.pop()
if __name__ == '__main__':
s = "14-3/2"
print(calculate(s))