How to process user supplied formulas?

前端 未结 3 473
孤城傲影
孤城傲影 2021-01-16 08:38

I have a dictionary containing a set of key values available through a web application: I want to process user supplied formulas like: ((value1+value3)/value4)*100

W

3条回答
  •  花落未央
    2021-01-16 09:16

    After validating both the formula and the numbers value (f.e. via a regexp) you can do something like:

    arr = {'num1':4, 'num2':5, 'num3':7}
    formula = '(num1+num2)*num3'
    
    for key, val in arr.items():
        formula = formula.replace(key, str(val))
    
    res = eval(formula)
    print res
    

提交回复
热议问题