简体   繁体   English

试图理解lambda中的“或”运算符

[英]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 该函数生成特定深度n的abacaba序列

For example: 例如:

n = 2, output: 'abacaba' n = 2,输出:'abacaba'

n = 3, output: 'abacabadabacaba' n = 3,输出:'abacabadabacaba'

The question is, how does the code work? 问题是,代码是如何工作的? Namely, how does "or" operator work inside lambda? 也就是说,“或”运算符如何在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; 如果or的左手参数是真实的,则表达式对此进行评估; 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 在这种情况下,当n > 0时, "a"[n:]是空字符串,所以它相当于

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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