Home > Enterprise >  Function within a function unknown number of times
Function within a function unknown number of times

Time:12-01

How do I use the output of one function as the argument of another. There is an unknown (X) number of functions and each function is different. The argument to the first function is known (lets call it n).

I have tried to create a list of the functions and use the results of one for another, I can't really get anywhere.

list = [function1, function2, function3, function4, function5.....functionX]

def nestedfunction(list, n):
    a_1 = list[0](n)
    a_2 = list[1](a_1)
    a_3 = list[2](a_2)
    a_4 = list[3](a_3)
    a_5 = list[4](a_4)
    ......
    a_x = list [len(list)-1](a_x-1)
    print (a_x)

Thank you for your help.

CodePudding user response:

Iterate over the list and overwrite n with each iteration, then return it:

def nestedfunction(function_list, n):
    for function in function_list:
        n = function(n)
    return n

CodePudding user response:

It's way easier than you made it:

funcs = [function1, function2, function3, function4, function5.....functionX]

def nestedfunction(funcs, n):
    for f in funcs:
        n = f(n)
    return n

CodePudding user response:

The other answers are the Pythonic way of doing this. But I just wanted to point out that this is a common pattern, and in functional programming we would recognize this as a reduction. So this is how we would do this operation:

>>> import functools
>>> funcs = [lambda x: x   42, lambda x: x % 12, lambda x: x*2]
>>> n = 0
>>> functools.reduce(lambda a, f: f(a), funcs, n)
12

Also note, we can use a related tool from the standard library if we want each individual step, using itertools:

>>> import itertools
>>> acc = itertools.accumulate(funcs, lambda a, f: f(a),  initial=n)
>>> for step in acc:
...     print(step)
...
0
42
6
12
  • Related