0

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".

1
  • You will need a lookup table. This table will store all valid operations you intend for your program to carry out. When you get the string, you parse it by removing all non alphanumeric characters (strings), then you use the lookup table to decide what operation needs to be done Commented Feb 21, 2014 at 17:36

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

3 Comments

eval is a builtin: it doesn't come from the math library.
I tried this exact code in Python command line to test it out, and I ended up getting: [True, False, False] When I try it in my own code: def getYTable(function, xlist): result = [] result.append(eval(function) for x in xlist) return result def Main(): ylist = getYTable("x**2", [1,2,3]) print(ylist) I end up getting [<generator object <genexpr> at 0xb72afd74>] What is going on here? eval is a bit new to me.
Never mind, I figured it out. def getYTable(function, xlist): #Write your implementation here result = [] for x in xlist: result.append(eval(function)) return result
0

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).

1 Comment

Drat, I somehow missed the last line of the question, C.B.s answer looks good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.