Program For Evaluating Postfix Expression Using Stacked
My task is to convert a fully parenthesized infix expression. Example(((54+56)+(4+73))+(9+7))to postfix. Then evaluate the postfix. The expression is input from the user.I have to use a class called Stack already written for me.
Evaluate Postfix Expression Java
It must not be modified: class Stack:def init(self):self.theStack=def top(self):if self.isEmpty:return 'Empty Stack'else:return self.theStack-1def isEmpty(self):return len(self.theStack)0def push(self,item):self.theStack.append(item)def pop(self):if not self.isEmpty:temp=self.theStack-1del(self.theStack-1)return tempelse:return 'Empty Stack'The first problem I have is that when the user inputs for example 54, while using stack, 5 and 4 are two different elements. How can I turn it into one?Here is the code I have so far so evaluating the postfix: OPERATOR='+','-','.' , '/'def evaluatePostfix(Postfix):eStack=Stackfor n in Postfix:if n not in OPERATOR and n!='(' and n!=')':eStack.push(n)if n in OPERATOR:math=eStack.pop+n+eStack.popeval(math)I know the problem is the second to last line but I'm not sure how to fix it.
There are a few questions you're asking (and your answer isn't complete, as far as leading you to your ultimate goal of evaluating a postfix expression), but let me address the one you ask:'The first problem I have is that when the user inputs for example 54, while using stack, 5 and 4 are two different elements. How can I turn it into one?' If you are committed to scanning the input one character at a time, then the simplest approach is to use a temporary variable. Here's a quick and dirty way to do it in Python.
Program For Evaluating Postfix Expression Using Stack In Java
Infix = '54 + 490'postfix = 'anumber = NoneOPERATOR = '+', '-', '.' , '/'for n in infix:if n not in OPERATOR and n!= '(' and n!= ')':if anumber is None:anumber = nelse:anumber = anumber + nif n is ')' or n in OPERATOR:if anumber is not None:postfix += anumberanumber = Noneif anumber is not None:postfix += anumberanumber = Noneprint postfix. When you write: for n in Postfixyou're iterating over the characters in Postfix one at a time. You might do better to convert Postfix to a list of strings with a helper function along these lines to pad the operators if they're not padded def foo(str):newstr = 'for x in str:if x not in '. ':newstr += ' ' + x + ' 'else:newstr += xreturn newstrso now you can change for n in Postfixto for n in foo(Postfix).splitand it should solve the problem of not handling numbers properly.split splits a string into a list of nonwhitespace strings, e.g. 'hello world' would become 'hello', 'world'.