Python: How to evaluate a function which is string?

前端 未结 5 2009
悲&欢浪女
悲&欢浪女 2021-01-16 23:22

I get some models from database as

f(t)=(2.128795454425367)+(208.54359721863273)*t+(26.098128487929266)*t^2+(3.34369909584111)*t^3+(-0.3450228278737971)*t^4+         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-16 23:30

    As NPE says, the right answer here is to write a parser (and simple interpreter) for your expression language.

    Or, even better, if at all possible, generate the expressions in Python in the first place, instead of in a language which is almost but not quite compatible with a subset of Python.

    Or, even better, if the language is just a way to represent the list of coefficients for a polynomial, just represent it as a list of coefficients, which will be a lot easier to parse than any actual general-purpose language. For example, let's say the database held this:

    2.128795454425367, 208.54359721863273, 26.098128487929266, 3.34369909584111, -0.3450228278737971, -0.018630757967458885, 0.0015029038553239819
    

    Then, to execute that in Python, you'd do this:

    def eval_polynomial(polynomial, value):
        coefficients = [float(x.strip()) for x in polynomial.split(',')]
        return sum(coefficient * (value**exponent) 
                   for exponent, coefficient in enumerate(coefficients))
    

    Then:

    >>> [eval_polynomial(expr, t) for t in range(1, 13)]
    

    But if you really, really want to do this without changing what's in the database, you could just transform it into a Python expression and eval it:

    >>> expr = 'f(t)=(2.128795454425367)+(208.54359721863273)*t+(26.098128487929266)*t^2+(3.34369909584111)*t^3+(-0.3450228278737971)*t^4+(-0.018630757967458885)*t^5+(0.0015029038553239819)*t^6;'
    >>> removef = re.sub(r'f\((\w+)\)=', 'lambda \1: ', expr)
    >>> fixpower = re.sub(r'(\w+)\^(\d+)', r'(\1**\2)', removef)
    >>> nosemi = fixpower.replace(';', '')
    >>> func = eval(nosemi)
    >>> [func(t) for t in range(1, 13)]
    [239.75206957484252, 544.337732955938, 921.544112756058, 1366.6221363666925, 1864.8848673959649, 2393.2591324279497, 2922.9192385578326, 3423.0027817028927, 3865.4085456893295, 4230.676492114911, 4514.949840987468, 4738.019242139209]
    

    But again, you probably don't want to do this.

    And, if you do, you probably want to write a transformer that works on your actual language, rather than on a stab-in-the-dark guess at your language based on a single example…

提交回复
热议问题