简体   繁体   中英

Trying to understand “or” operator inside lambda

I came across following code while solving this problem:

f=lambda n:"a"[n:]or f(n-1)+chr(97+n)+f(n-1)

The function generates abacaba sequence of specific depth n

For example:

n = 2, output: 'abacaba'

n = 3, output: 'abacabadabacaba'

The question is, how does the code work? Namely, how does "or" operator work inside lambda? (I assume code above uses recursion, and to my knowledge, normally we use loops for recursion, but I don't see anything that resembles loops in the code above)

It works the same way it does anywhere else. If the left-hand argument of or is truthy, the expression evaluates to that; otherwise, it evaluates to the right-hand argument. In this case, "a"[n:] is the empty string when n > 0 , so it's equivalent to

def f(n):
    if n == 0:
        return "a"
    else:
        return f(n-1) + chr(97+n) + f(n-1)

Let's break it down.

f = lambda # declare a variable f that is a function
n:         # that takes an int parameter 'n'
"a"[n:]    # if n is 0 return 'a'
or         # else
f(n-1)     # return a recursive call at n - 1
+          # plus
chr(97+n)  # character from code 97 + n
+          # plus
f(n-1)     # another recursive call

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