-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
110 lines (85 loc) · 2.97 KB
/
__main__.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import sys
import math
#interprete the user input smt like this
line = input(f"\nEnter your numbers and operators >> ")
line = line.strip()
parts = line.split(" ")
program = []
for part in parts:
if line == "":
continue
try:
if part.isdigit():
program.append(int(part))
elif part in ["+", "-", "*", "/"]:
program.append(part)
except:
raise Exception("Error: well well well. what did you enter? check your input")
#you can delete this line, it is for testing only
print(" >> the numbers you entered: ", program, "\n")
#the calculator class
#takes the interpreted input and calculates the result depending on operators and other shi
class Calculator:
def __init__(self, program):
self.pc = 0
self.result = None
def calculate(self):
self.pc = 0
try:
while self.pc < len(program):
self.result = None
opcode = program[self.pc]
#print(f"{self.result}, {self.pc}, {program}")
if opcode == "*":
self.result = program[self.pc-1]
a = self.result
b = program[self.pc+1]
self.result = a * b
print(f">>> {a} * {b} = {self.result}")
program[self.pc-1] = self.result
program.pop(self.pc)
program.pop(self.pc)
self.pc -= 1
elif opcode == "/":
self.result = program[self.pc-1]
a = self.result
b = program[self.pc+1]
self.result = a / b
print(f">>> {a} / {b} = {self.result}")
program[self.pc-1] = self.result
program.pop(self.pc)
program.pop(self.pc)
self.pc -= 1
self.pc += 1
except:
raise Exception("Error 1: something went wrong, check your input")
self.pc = 0
try:
while self.pc < len(program):
self.result = None
opcode = program[self.pc]
#print(f"{self.result}, {self.pc}, {program}")
if opcode in ["+", "-", "*", "/"]:
if opcode == "+": #this is the addition
a = program[self.pc-1]
b = program[self.pc+1]
self.result = a + b
print(f">>> {a} + {b} = {self.result}")
program[self.pc-1] = self.result
program.pop(self.pc)
program.pop(self.pc)
self.pc -= 1
if opcode == "-": #this is the subtraction
a = program[self.pc-1]
b = program[self.pc+1]
self.result = a - b
print(f">>> {a} - {b} = {self.result}")
program[self.pc-1] = self.result
program.pop(self.pc)
program.pop(self.pc)
self.pc -= 1
self.pc += 1 #move to the next opcode, making the result the first operand for the next operation
except:
raise Exception("Error 2: something went wrong, check your input")
calculator = Calculator(program) #starting and running the calculator
calculator.calculate()