A. Fattal
A. Fattal

Reputation: 77

Is there a way I can set a math function as a parameter for another function

For example, let's say you want to create a function that yields double the function at a certain value, like this:

def doubler(f(x),n):
    return 2*f(n)

Example:

doubler(2*x,1)

would yield 4 (2*(2*1))

The reason I want to do this is because I'm creating a module that allows someone to solve various problems, such as normalizing a wave function of a system (so the function of x will be a parameter, i.e input)

Upvotes: 0

Views: 436

Answers (2)

M-Chen-3
M-Chen-3

Reputation: 2054

You can, but you need to pass in an actual function. lambda will create a single-use function that you can pass in to doubler.

def doubler(func, x):
    return func(x)*2

print(doubler(lambda x: x*2, 2))
# Prints 8

Alternatively, you can pass in a named function.

def doubler(func, x):
    return func(x)*2

def f(x):
    return x*2

print(doubler(f, 2))
# Still prints 8

EDIT: Another, NOT RECOMMENDED, way is using eval.

Note that this requires inputting a string, and that if you allow for user input, you'll likely want to filter the input to make sure they can't run Python code.

def doubler(func,n):
    x = n
    return 2*eval(func)

print(doubler("x**2", 3))
# Prints 18

Upvotes: 4

user2390182
user2390182

Reputation: 73450

I think you are aiming for the following:

def doubler(f):
    def inner(n):
        return 2 * f(n)
    return inner

def square(n):
    return n**2

>>> double_square = doubler(square)
>>> double_square(3)
18
>>> double_square(4)
32

Note that the doubler function returns a function itself which encapsulates the desired behaviour. Alternatively, closer to what you describe, you can pass both function and parameter:

def doubler(f, x):
    return 2 * f(x)

>>> doubler(square, 3)
18
>>> doubler(square, 4)
32

But the benefit of this is not immediately obvious, as you could just pass square(3) or square(4) as an argument to a much simpler function.

Upvotes: 2

Related Questions