This is my solution for evaluating postfix expression using a stack. It does work on multidigit numbers, the problem I was struggling with last time. Now it works completely fine.
This is the stack that I'm using:
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
self.items.pop()
def peek(self):
try:
return self.items[-1]
except:
return False
def value_at_index(self, value):
try:
return self.items[value]
except:
return False
def all_items(self):
return self.items
And here is my code:
def result(data):
"""Evaluating postfix expression"""
stack = Stack()
if data != False:
for element in data:
try:
if type(float(element)) == float:
stack.push(element)
except:
method = "float(stack.value_at_index(-2))" + element + "float(stack.value_at_index(-1))"
method = eval(method)
stack.pop()
stack.pop()
stack.push(method)
return stack.peek()
else:
return "Check your formula"
data = ['20', '10', '+', '75', '45', '-', '*']
print(result(data))
Output:
900.00
It works perfectly fine, but to be completely honest i would like to get rid of eval
because of the negative opinions on this built-in function I heard. I want some reviews from you guys and advices how to generally improve it.
Using Python 3.6.7.
index_of_element
actuallyvalue_at_index
? \$\endgroup\$element
have you observedtype(float(element)) == float
to be false? \$\endgroup\$