Simple Infix to Postfix in Python

Today I wrote a Python program to transform an expression to reverse polish notation in order to solve the problem Transform the Expression and it worked fine. Here is my code:
def rpn(s):
    var_list = []
    symb_list = []
    for c in s:
        if c >= 'a' and c <= 'z':
            var_list.append(c)
        elif c in ['^', '*', '/', '+', '-']:
            symb_list.append(c)
        elif c == ')':
            x = var_list.pop()
            y = var_list.pop()
            z = symb_list.pop()
            var_list.append(y + x + z)
        #print var_list, symb_list
        
    return var_list[0]
        
t = int(raw_input())

while t:
    t -= 1
    s = raw_input()        
    print rpn(s)
The algorithm is very simple which you should be able to follow if you study my code. You can uncomment the line #print var_list, symb_list to see a simulation. Note that the Python program I wrote is not the perfect infix to postfix converter but it worked for the problem. The ideal program should work without taking the advantage of brackets. :-)

Comments

Unknown said…
Instead of using " if c >= 'a' and c <= 'z':" , use of " c.isaplpha() " will be more efficient, isn't it?
Tamim Shahriar said…
There is no noticeable performance difference but c.isalpha() looks better.

>>> timeit.timeit('"c".isalpha()', number=100000)
0.010938495863229036
>>> timeit.timeit('"c" >= "a" and "c" <= "z"', number=100000)
0.00959616294130683
>>> timeit.timeit('"c" >= "a" and "c" <= "z"', number=100000)
0.011491957120597363
>>> timeit.timeit('"c".isalpha()', number=100000)
0.01122324913740158
>>>

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code