Saar Gamzo
Saar Gamzo

Reputation: 53

Python lambda return value

I'm learning the lambda options to return in python and i have a question:

I need to fill the returns in this function:

def func(n):
   if n==0:
      print("finished")
   else:
      return ___
func(5)()()()()()
func(3)()()()
func(8)()()()()()()()()

The output:

finished
finished
finished

I thought this one is a recursive call like return func(n-1) but it doesn't work, and throws an error. Is there an option to overcome the extra empty brackets? count them? do something, because it should be runnable.

Thanks

Upvotes: 0

Views: 1510

Answers (2)

simre
simre

Reputation: 658

The operator () is the function call. So for example:

def foo():
   print('Foo executed')

def bar():
   # We return the foo FUNCTION itself, without calling it.
   return foo

In the above code, if you execute foo(), it'll print "Foo executed". But if you execute bar(), it will return foo, which is the function. So you can execute bar()(), where the first () is executing the function bar, returning foo, and then with the second (), you call the returned foo function.

Edit: When I typed it, you removed the what are those bunch of () because they are new to you... But I just leave it there maybe it'll help.

Upvotes: 0

Sayse
Sayse

Reputation: 43300

You're right about needing to use lambdas and func n-1, specifically

return lambda: func(n-1)

This returns a lambda that doesn't need any parameters passed in, to handle the brackets, and the return of the is the function being called with n-1, which in most calls you're making, is returning the next lambda function call

Upvotes: 1

Related Questions