shiba kandel
shiba kandel

Reputation: 1

Break a math expression up into a list of its parts, separating the numbers from the operators

I tried:

tokens = [t.strip() for t in re.split(r'((?:-?\d+)|[+\-*/()])', exp)]  
return [t for t in tokens if t != '']

But it gets the wrong result:

Expected :[3, '+', -4, '*', 5]

Actual   :['3', '+', '-4', '*', '5']

Upvotes: 0

Views: 106

Answers (2)

Patrick Haugh
Patrick Haugh

Reputation: 60974

You need to cast the items in the list to ints where appropriate

def try_int(s):
    try:
        return int(s)
    except ValueError:
        return s

Then in your function, you can apply this to all the items in the return list

return [try_int(t) for t in tokens if t != '']

Upvotes: 1

jeevaa_v
jeevaa_v

Reputation: 423

Use a for loop without the syntactic sugar. Convert the str of the integers to int using string method isdigit().

Example:

>>> "4".isdigit()
>>> True

Upvotes: 0

Related Questions