Programmingfreak
Programmingfreak

Reputation: 61

unsupported operand type(s) for ** or pow(): 'function' and 'int'

This is my code, can you please tell me what is causing the error when printing? The function compose is supposed to compute function composition.

def compose(lst):
    return acc(g, h, lst)
print(compose([lambda x:x**2,lambda y:2*y])(5))
def acc(f, v, lst):
    if len(lst)==0:
        return v
    if len(lst)==1:
        return f(v,lst[0])
    return f(lst[0], acc(f,v,lst[1:]))
def h(f):
     return f
def g(f1,f2):
     return f1(f2)

Upvotes: 0

Views: 1406

Answers (2)

Mike Müller
Mike Müller

Reputation: 85482

You need to make a function g that actually calls f2 with arguments:

def g(f1, f2):
    def func(*args, **kwargs):
        return f1(f2(*args, **kwargs))
    return func

print(compose([lambda x: x**2, lambda y: 2*y])(5))

Output:

100

This is equivalent to:

>>> (lambda x: x**2)((lambda y: 2*y)(5))
100

Upvotes: 2

n.caillou
n.caillou

Reputation: 1342

At the last line f1(f2), the argument given to f1 is f2 (a lambda), not the int 5.

You need to do something like lst[0](lst[1](x))

Upvotes: 1

Related Questions