How to evaluate a custom math expression in Python

Posted by taynaron on Stack Overflow See other posts from Stack Overflow or by taynaron
Published on 2010-04-15T04:03:48Z Indexed on 2010/04/15 4:13 UTC
Read the original article Hit count: 276

Filed under:
|
|

I'm writing a custom dice rolling parser (snicker if you must) in python. Basically, I want to use standard math evaluation but add the 'd' operator:

#xdy
sum = 0
for each in range(x):
    sum += randInt(1, y)
return sum

So that, for example, 1d6+2d6+2d6-72+4d100 = (5)+(1+1)+(6+2)-72+(5+39+38+59) = 84

I was using regex to replace all 'd's with the sum and then using eval, but my regex fell apart when dealing with parentheses on either side. Is there a faster way to go about this than implementing my own recursive parsing? Perhaps adding an operator to eval?

© Stack Overflow or respective owner

Related posts about python

Related posts about eval