Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I came across this version of the factorial exercise and am completely at sea:

(我遇到了这种形式的阶乘练习,并且完全在海上:)

fac = lambda n: n and n * fac(n-1) or 1

It's the and/or part that I can't get my head around -- particularly the n and ... part.

(这是和/或部分,我不能左右我的头-尤其是N和...的一部分。)

Last: when you run this without the n and ... part, it returns a "maximum recursion depth exceeded" error.

(上一个:如果您在不使用n and ...部分的情况下运行此命令,则会返回“超出最大递归深度”错误。)

  ask by Pascal80 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
266 views
Welcome To Ask or Share your Answers For Others

1 Answer

It's a "clever" way of writing an if / else expression .

(这是编写if / else表达式的一种“聪明”的方式。)

It would be better expressed using those keywords instead:

(最好使用这些关键字来表示:)

fac = lambda n: n * fac(n-1) if n else 1

Or even more explicitly:

(或更明确地说:)

fac = lambda n: (n * fac(n-1) if n != 0 else 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...