LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   error in reading lines.. (http://www.linuxquestions.org/questions/linux-newbie-8/error-in-reading-lines-4175435630/)

NickPats 11-04-2012 06:34 PM

error in reading lines..
 
i am converting infix to postfix.. but when i try to read expressions from file (line by line). its just giving me not what i want.

Code:


postfix = []
temp = []
operator = -1
operand = -2
leftparent = -3
rightparent = -4
empty = -5

def precedence(s):
        if s is '(':
                return 0
        elif s is '+' or '-':
                return 1
        elif s is '*' or '/' or '%':
                return 2
        else:
                return 99

def typeof(s):
        if s is '(':
                return leftparent
        elif s is ')':
                return rightparent
        elif s is '+' or s is '-' or s is '*' or s is '%'or s is '/':
                return operator
        elif s is ' ':
                return empty
        else :
                return operand

lines = [line.strip() for line in open('tem')]

for i in line :
        type = typeof(i)
        if type is leftparent :
                temp.append(i)
        elif type is rightparent :
                next = temp.pop()
                while next is not '(':
                        postfix.append(next)
                        next = temp.pop()
        elif type is operand:
                postfix.append(i)
        elif type is operator:
                p = precedence(i)
                while len(temp) is not 0 and p <= precedence(temp[-1]) :
                        postfix.append(temp.pop())
                temp.append(i)
        elif type is empty:
                continue

while len(temp)>0:
  postfix.append(temp.pop())

print "It's postfix notation is ",' '.join(postfix)


chrism01 11-04-2012 06:53 PM

1. which language is this?
2. when posting, use square brackets [ ] to mark code, not < > https://www.linuxquestions.org/quest...do=bbcode#code
3. please show an example of input and output, also desired output

NickPats 11-04-2012 07:01 PM

its in python ...
tried 13 + 23 - 42 * 2

gives me 1 3 2 3 + 4 2 - 2
* (gives me * operator in new line and space between digits)
wants : 13 23 + 42 - 2 *

there is input file which has this samples:
677 + 127 - 456
24 - 17 + 13
4 * ( 5 - 3 )

output
677 127 + 456 -
24 17 - 13 +
4 5 3 - *


All times are GMT -5. The time now is 08:35 AM.