Composing functions in python

前端 未结 12 1224
北荒
北荒 2020-11-27 03:56

I have an array of functions and I\'m trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compo         


        
12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 04:04

    def compose (*functions):
        def inner(arg):
            for f in reversed(functions):
                arg = f(arg)
            return arg
        return inner
    

    Example:

    >>> def square (x):
            return x ** 2
    >>> def increment (x):
            return x + 1
    >>> def half (x):
            return x / 2
    
    >>> composed = compose(square, increment, half) # square(increment(half(x)))
    >>> composed(5) # square(increment(half(5))) = square(increment(2.5)) = square(3.5) = 12,25
    12.25
    

提交回复
热议问题