Question

So I have a function that takes a math equation in string format, and a list of numbers.

The purpose of the function is to apply that function to each number (an exponent function), and return the result.

For example, I am trying to pass "x**4" to it, and the list [4,3,2]

The end result, of course, would be [256, 81, 16]

How do you convert the string to a math equation while also keeping in mind that the string could be anything from "x*2" or "x*3".

Was it helpful?

Solution

Use the eval function , and use a list comprehension. This requires you know the var name ahead of time. If you don't, parse it then use this.

>>> operation = "x**4"
>>> num_list = [4,3,2]
>>> [eval(operation) for x in num_list]
[256, 81, 16]

OTHER TIPS

Depends how complicated you need it to be. Could you use the map builtin like:

x = [4, 3, 2]

def exp4( val ):
    return val ** 4

map( exp4, x )

You define the functions you need and apply them as an when. You've not said if you need an abilty to pick functions dynamically and it presumes an itterable (list in this case).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top