Aug-29-2018, 11:16 AM
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!
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")