In: Computer Science
I need to write an interpreter for arithmetic expressions in Python. This program receives an input string with an arithmetic expression and does:
1. prints a ">>>" as if it was a terminal
2. lets us allocate a variable to a a numeric value (as "a = 3") then it stores {'a':3} to a dictionary memory
3. whenever it receives an expression or input, transform it to postfix notation and print it (even when allocating variables)
4. it is able to operate with alerady allocated variables (so if i did put a = 2, then I can create expressions with A that will have a real value)
5. Stores and evaluates postfix notation expression in stacks
6. Is able to operate with the operands:
a. "(" ")" parethesis
b. unary + and unary -
c. exponentiation
d. multplication and division
e. binary sum and binary subtraction
when I type (__quit__) quits the program.
7. the program must be able to let me allocate variables to more than one digit strings (as 'yee') and operate with more than one digit numbers.
top = -1
array = []
output = []
precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
alpha_value = {}
def push(op):
global top
top += 1
array.append(op)
def pop():
global top
if top != -1:
top -= 1
return array.pop()
else:
return "$"
def checkHigher(ch):
result = False
if ch in precedence and array[-1] in precedence:
if precedence[ch] <= precedence[array[-1]]:
result = True
return result
while True:
input_str = input(">>")
if input_str == "(__quit__)":
break
if "=" in input_str:
a_v = input_str.split("=")
alpha_value[a_v[0]] = a_v[1]
else:
for ch in input_str:
if ch.isalpha():
output.append(ch)
elif ch == "(":
push(ch)
elif ch == ")":
while top != -1 and array[-1] != "(":
output.append(pop())
if top != -1 and array[-1] != "(":
break
else:
pop()
else:
while top != -1 and checkHigher(ch):
output.append(pop())
push(ch)
while top != -1:
output.append(pop())
last = []
for i in output:
if i in alpha_value:
last.append(alpha_value[i])
else:
last.append(i)
print("".join(last))