Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call 2 functions in a function [duplicate]

The problem is as follows below:

Write a function compose that takes two functions as argument, we call them Fa and Fb, and returns a function, Fres, that means that outdata from the other function is indata to the first, ex: Fres(x) = Fa(Fb(x)). run example:

>>> def multiply_five(n):
... return n * 5
...
>>> def add_ten(x):
... return x + 10
...
>>> composition = compose(multiply_five, add_ten)
>>> composition(3)
65
>>> another_composition = compose(add_ten, multiply_five)
>>> another_composition(3)
25

So as I understand this if I send in 3 the function compose will take 3+10 = 13 after that send that result into the multiply function it will do: 13*5 witch is 65. this is the code I've written so far:

def multiply_five(n):
    return n*5

def add_ten(x):
    return x+10

def compose(func1, func2):
    def comp(arg):
        return func2(arg)
    return func1(comp(arg))

I get compile error, and I've tried some different approaches:

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    composition = compose(multiply_five, add_ten)
  File "C:\Users\Jim\Desktop\tdp002\5h.py", line 10, in compose
    return func1(comp(arg))
NameError: name 'arg' is not defined
like image 649
Jim Avatar asked Sep 16 '25 08:09

Jim


1 Answers

You don't want to call either func1 or func2 yet; you just want to return a function that will call them both.

def compose(func1, func2):
    def _(*args, **kw):
        return func1(func2(*args, **kw))
    return _

You could also just use a lambda expression to create the composed function.

def compose(func1, func2):
    return lambda *args, **kw: func1(func2(*args, **kw))
like image 76
chepner Avatar answered Sep 19 '25 05:09

chepner