Discussion:
[Tutor] infix to postfix eval
Quiles, Stephanie
2015-08-02 04:09:36 UTC
Permalink
hello again!

I have to unify these methods so that i can enter an infix, convert it to a postfix and then solve. Here are the methods

method #1 is :


class Stack:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def push(self, item):
self.items.insert(0,item)

def pop(self):
return self.items.pop(0)

def peek(self):
return self.items[0]

def size(self):
return len(self.items)


def infixToPostfix(infixexpr):
prec = {}
prec["^"] = 4
prec["*"] = 3
prec["/"] = 3
prec["+"] = 2
prec["-"] = 2
prec["("] = 1
opStack = Stack()
postfixList = []
tokenList = infixexpr.split()

for token in tokenList:
if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
postfixList.append(token)
elif token == '(':
opStack.push(token)
elif token == ')':
topToken = opStack.pop()
while topToken != '(':
postfixList.append(topToken)
topToken = opStack.pop()
else:
while (not opStack.isEmpty()) and \
(prec[opStack.peek()] >= prec[token]):
postfixList.append(opStack.pop())
opStack.push(token)

while not opStack.isEmpty():
postfixList.append(opStack.pop())
return " ".join(postfixList)

print(infixToPostfix("5 * 3 ^ ( 4 - 2 )"))
print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )”))


method #2 is :

def postfixEval(postfixExpr):
operandStack = Stack()

tokenList = postfixExpr.split()

for token in tokenList:
if token in "0123456789":
operandStack.push(int(token))
else:
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token,operand1,operand2)
operandStack.push(result)

return operandStack.pop()

def doMath(op, op1, op2):
if op == "^":
return op1 ** op2
if op == "*":
return op1 * op2
elif op == "/":
return op1 / op2
elif op == "+":
return op1 + op2
else:
return op1 - op2

basically i have to make a main function and somehow unify these two so that user can input an infix, then convert and print the postfix and then solve and print the final calculation. Here is the assignment as written by the instructor:

Try to do program #3 from P.144. We began this in class. Here’s what you need to do. We will be using Listings 3.7 and 3.8. First make sure that you can get Listing 3.7 to work. Just test some strings. Note that the code in the text expects the input to be “strings” of letters, each character separated by a space, and uses the “uppercase” statement in its definition. Second make sure that you can get Listing 3.8 to work. Just test some strings. This one you will test with digits. Third, now what you’ll need to do to answer program #3 is to get Listing 3.7 to handle digits rather than letters. This should not require a great deal of change to the code. Look at how Listing 3.8 handles the digits and see if you can duplicate that. Test some simple examples (limit the values from 0 – 9) with each character (token) separated by a space. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * +. (NOTE THE SPACES.) Fourth, once you have this working, you will simply feed this result to Listing 3.8 and the evaluated result should be printed. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * + and also output the value of 11.

Below is a sample of what you could show. Keep it simple.


print ("This program will accept an infix expression,")
print ("convert to postfix, and evaluate the result.")
print ("No input validation will be performed.")
print ("Please enter the infix expression correctly, as follows:")
print ("Enter only numbers 0-9")
print ("Separate each character with a space")
print ("You can use the following operators: ( ) + - * / ")
print ("For example: ( 8 + 2 ) * ( 2 + 4 )")

Here’s how a sample run would look.

This program will accept an infix expression,
convert to postfix, and evaluate the result.
No input validation will be performed.
Please enter the infix expression correctly, as follows:
Enter only numbers 0-9
Separate each character with a space
You can use the following operators: ( ) + - * /
For example: ( 8 + 2 ) * ( 2 + 4 )

Enter infix string: ( 8 + 2 ) * ( 2 + 4 )
The postfix string is: 8 2 + 2 4 + *
The final result is: 60

Thanks!

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Anish Tambe
2015-08-03 06:00:31 UTC
Permalink
On Sun, Aug 2, 2015 at 9:39 AM, Quiles, Stephanie
Post by Quiles, Stephanie
hello again!
I have to unify these methods so that i can enter an infix, convert it to a postfix and then solve. Here are the methods
At the end of your code I added this -

inFixExpr = raw_input("Enter infix string : ")
postFixExpr = infixToPostfix(inFixExpr)
print("The postfix string is: " + postFixExpr)
value = postfixEval(postFixExpr)
print("The final result is: " + str(value))

And this gives me output -
$ python postfix.py
5 3 4 2 - ^ *
A B + C * D E - F G + * -
Enter infix string : ( 8 + 2 ) * ( 2 + 4 )
The postfix string is: 8 2 + 2 4 + *
The final result is: 60
Instead of the above line, you can do this -
if token in string.uppercase or token in string.digits:
Import string module first.
Post by Quiles, Stephanie
import string
string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Post by Quiles, Stephanie
string.digits
'0123456789'
Thanks,
Anish
_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
Laura Creighton
2015-08-03 07:28:46 UTC
Permalink
Hi Anish.

I wanted to let you know something I found out last week.
Even when you select plain text email, gmail will mangle
any lines of text starting with one or more '>' marks.
import string
string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits
'0123456789'
except all flush with the left margin, gmail thinks that it would be a
great idea to reflow this text, as if this was a quoted text from
somebody else.

Until we can get Google to stop doing this, the work-around is to
indent your output from the python console, or change your python
console prompt to py> or something. The values of the prompts are
stored in sys.ps1 and sys.ps2 and you can change them to whatever you
like.

Just thought you would like to know,
Laura

_______________________________________________
Tutor maillist - ***@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Loading...