Say I have 50,000 lines of string that contain simple mathematical expression (only +,- operator involve e.g. 1+2+3+5). I know that it is handy to use eval() in Python to evaluate those strings. However, the program is not efficient enough. I ran the cProfile and found most of the bottleneck is from the eval function (around 2.5 secs in 50,000 lines case). I've tried to write my own evaluation parser but it perform even slower then the eval.
So, what I want to ask is if there are any way to fast evaluate mathematical expression strings or improve the performance of eval()? Third-party package cannot be used.
The original problem is like this We have a string of digit like 1234567 and we can insert +,-,or nothing between the digits like 1+23-4+56-7. So there will be 3^(digit-1) combinations for a given number string
What I implement in Python to calculate and generate string like the following
import itertools
def gen_Eq(op, num):
temp = [None]*(2*len(num)-1)
temp[::2] = num
temp[1::2] = op
string = ''.join(temp)
return string
def cal_Eq(num_string):
op_list = tuple(itertools.product(['+','-',''],repeat=len(num_string)-1))
eq = list(map(gen_Eq,op_list,itertools.repeat(num_string,len(op_list))))
print map(eval,eq)