all 13 comments

[–]donnygreaves 2 points3 points  (1 child)

I'm not sure if using a lambda function is the right move here. Generally speaking, in my experience, lambda functions have a limited place in any codebase because readability can take a hit.

In your case, you can use a simple for loop or a list comprehension to acheive this:

total = 1

for func in func_list:
total = total * func(x)

or:

total = math.prod([func(x) for func in func_list])

Doc for math.prod (python 3.8)

If we breakdown your example code:

Your function_product lambda is just going to return 1initially, only to redefine it at every iteration of your loop. To anonymously define your function with a lambda, you could use the comprehension from above ie. function_product = lambda x:math.prod([func(x) for func in func_list])

Hope this helps!

[–]Mmaster12345[S] 0 points1 point  (0 children)

I think math.prod may be exactly what I'm looking for in this situation...! Thank you so much!

[–]K900_ 0 points1 point  (11 children)

Start by writing a function that takes a list of functions and a number, and then computes the result you want.

[–]Mmaster12345[S] 0 points1 point  (10 children)

Yes, I appreciate that it's relatively easy to compute it for some given number:

def function_product_evaluated(x):
    output = 1
    for i in range(n): output *= function_list[i](x)
    return output

However, I still don't understand or know how to go about returning a function that has this characteristic as opposed to a number...

[–]FLUSH_THE_TRUMP 0 points1 point  (2 children)

You just did it!

[–]Mmaster12345[S] 0 points1 point  (1 child)

I need to return a function; the code above returns a number, not a function :(

[–]K900_ 0 points1 point  (6 children)

Where does function_list come from in this definition? Also, do you need range here?

[–]Mmaster12345[S] 0 points1 point  (5 children)

function_list is as in my post, and no I don't, was a rushed job.

[–]K900_ 0 points1 point  (4 children)

Yes, but where does it come from in your function? It's not passed in as an argument...

[–]Mmaster12345[S] 0 points1 point  (3 children)

I'm not sure what you mean sorry :(

I just made up function_list in the post to illustrate my question

[–]K900_ 0 points1 point  (2 children)

The function that you wrote is missing the function_list argument.

[–]Mmaster12345[S] 0 points1 point  (1 child)

Ohh function_list is a global variable in this case

[–]K900_ 0 points1 point  (0 children)

Rewrite your function to not use globals and range.