Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - Python中的Lambda递归和AND / OR(Lambda recursion and AND/OR in Python)

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

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

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...