My assignment was to write a function that computes the value of an expression written in infix notation. We assume that we are using the four classical arithmetic operations +, -, * and / and that each binary operation is enclosed in parentheses.
My stack:
class Stack:
def __init__(self):
self._arr = list()
def push(self, item):
self._arr.append(item)
#return self
def pop(self):
assert not self.is_empty(), "pop() on empty stack"
return self._arr.pop()
def is_empty(self):
return not bool(self._arr)
def peek(self):
assert not self.is_empty(), "peek() on empty stack"
return self._arr[-1]
def all_items(self):
return self._arr
def value_at_index(self, value):
try:
return self.items[value]
except:
return False
def __len__(self):
return len(self._arr)
The code:
def infix_brackets_eval(data):
Stack = Stack()
i = 0
ret = 0
while i < len(data):
if data[i] != ' ':
if data[i] not in '+-*/()':
temp = 0
while data[i] != ' ' and data[i]!= ')':
temp = temp * 10 + int(data[i])
i+=1
i-=1
elif data[i] == ')':
B = Stack.peek()
Stack.pop()
x = Stack.peek()
Stack.pop()
A = Stack.peek()
Stack.pop()
if Stack.peek() == '(':
Stack.pop()
if x == '-':
temp = A - B
elif x == '+':
temp = A + B
elif x == '*':
temp = A * B
elif x == '/':
temp = A / B
else:
temp = data[i]
#print(temp)
Stack.push(temp)
i += 1
return Stack.peek()
infix_brackets_eval("((12 * 3) + (2 + 3) * (1 * 3))")
Output:
15
Apart from the code comments of course, could any of you point me to an example use of a tokenizer or parser? I am very curious about the application and mechanics of how to use it, in the case when the tokens are operands, tokenize also need multi-digit numbers. Unfortunately I do not know where to look. I tried to rely on various documentation but I can not translate it to this example.
Stack
is almost exactly the same as in Kermit's question \$\endgroup\$