Python Forum
Shanting Yard Algorithm basic implementation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Shanting Yard Algorithm basic implementation
#1
Hey there!

I wanted to write the Shanting yard algorithm for solving algebraic expressions as a warm up exercise after taking a break from coding ...

So to understand it all I want to use only the most basic tools.
Now I get an out of index range error here because my operators stack is of zero length at the beginning.
I`m looking for a clever way to 'filter' that case out, because I wanna subtract 1 at the end since indexing starts at zero right? But index of -1 sucks aswell...
and ignore the print statements they are for debugging i guess haha
Thx for reading that far and I hope for your help!

def parse(exp):
    lexp = len(exp)
    output=[]
    ops=[]
    high={"-":1,"+":2,"/":3,"*":4,"^":5}
    while int(lexp) != 0:
        lexp = len(exp)
        token = exp[:1]
        exp = exp[1:]
        if token in '+-*/^()':
            pass
        elif token in '0123456789':
            token=int(token)

        if type(token) is int:
            output.append(token)
            print("int push to output")
        elif token in '+-*/^':
            while (( high[ops[len(ops)-1]] > high[token] )or((high[ops[len(ops)-1]]==high[token])and ops[len(ops)-1] in '+-*/')and(ops[len(ops)-1]!='(')):
                output.append(ops.pop())
                print("token seems to be op")
        elif token =='(':
            ops.append(token)
            print("bracket open")
        elif token ==')':
            while ops[len(ops)-1] != '(' :
                output.append(ops.pop())
            ops.pop()
            print("bracket closed")
        else:
            print("did nothing moo")
    if lexp == 0:
        while len(ops)!=0 :
            output.append(ops.pop())
        print("decap ops")



parse("2+3*4")
Reply
#2
You should have a case for the empty operator stack on line 19. See the Wikipedia version, it has it.

A few things: x[len(x) - 1] is excessive, as it is no different than x[-1]. You don't need int(lexp) on line 6 (len returns an int). if x: pass; elif y: do can be shortened to if y: do in every case.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Basic binary search algorithm - using a while loop Drone4four 1 378 Jan-22-2024, 06:34 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020