python - Parsing maths expression -
so following code function: "eqn" converts string: "d" mathematical expression, list of integers , operators according reverse polish notation, "add", "subtract", "multiply" , "divide" represent +, -, * , / respectively. there "negate" operator takes positive integer , turns negative integer. example inputs , outputs:
- eqn("10 5 add") should produce output of [10, 5 , "add"]
- eqn("5 6 add 2 negate divide") should produce output of [5, 6, "add", -2, "divide"]
with negative function though, if not used correctly (not after number) function should return index number of first incorrect "negate".
for example:
- eqn("negate 2 add 2") should produce output of 0
eqn("2 4 add negate") should produce output of 3
def eqn(d): extrac = [] e in eqnstr.split(): if len(e) == 0: continue try: extrac.append(int(e)) continue except valueerror: pass try: extrac.append(float(e)) continue except valueerror: pass extrac.append(e) return extrac
the problem negate function won't work. instead of changing integer negative comes out "negate" in output when should 'disappear'. example:
eqn("5 6 add 2 negate divide") should produce output of [5, 6, "add", -2, "divide"] instead produces [5, 6, "add", 2, "negate", "divide"] how fix , how show index number of first invalid negate?
you need add special case handle negate. try this:
def eqn(d): extrac = [] e in d.split(): if len(e) == 0: continue try: extrac.append(int(e)) continue except valueerror: pass try: extrac.append(float(e)) continue except valueerror: pass if e == 'negate': if isinstance(extrac[-1], str): return len(extrac) else: extrac[-1] *= -1 continue extrac.append(e) return extrac
output:
eqn("2 4 add negate") => 3 eqn("5 6 add 2 negate divide") => [5, 6, 'add', -2, 'divide']
Comments
Post a Comment