Composing functions in python

前端 未结 12 1221
北荒
北荒 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:06

    This is my version

    def compose(*fargs):
        def inner(arg):
            if not arg:
                raise ValueError("Invalid argument")
            if not all([callable(f) for f in fargs]):
                raise TypeError("Function is not callable")
            return reduce(lambda arg, func: func(arg), fargs, arg)
        return inner
    

    An example of how it's used

    def calcMean(iterable):
        return sum(iterable) / len(iterable)
    
    
    def formatMean(mean):
        return round(float(mean), 2)
    
    
    def adder(val, value):
        return val + value
    
    
    def isEven(val):
        return val % 2 == 0
    
    if __name__ == '__main__':
        # Ex1
    
        rand_range = [random.randint(0, 10000) for x in range(0, 10000)]
    
        isRandIntEven = compose(calcMean, formatMean,
                                partial(adder, value=0), math.floor.__call__, isEven)
    
        print(isRandIntEven(rand_range))
    

提交回复
热议问题