简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM