[英]Python 2.7 code, need explanation
def fact( n ):
"""fact( number ) -> number
Returns the number of permutations of n things."""
if n == 0:
return 1L
return n*fact(n-1L)
Anyone can explain me what this code does? 任何人都可以解释一下这段代码的作用吗? I am confused about the return statement ... n*fact(n-1L)!
我对return语句感到困惑... n * fact(n-1L)! This seems Infinite for me :/
对我来说,这似乎是无限的:/
Thanks. 谢谢。
This is a recursive function. 这是一个递归函数。
if n == 0:
if n == 0:
This is pretty self explanatory. 这是不言自明的。 In this
if
statement, we check to see if n
is equal to 0
. 在此
if
语句中,我们检查n
是否等于0
。
return 1L
return 1L
If n
is indeed equal to 0
, we return 1L
(1 Long
, or essentially 1
in this case.) Note, that if we get to this return
, we do not go on to the 3 rd line because a return
is like a break
. 如果
n
确实等于0
,则返回1L
(1 Long
,在这种情况下本质上为1
)请注意,如果到达该return
,则不继续执行第三行,因为return
就像是break
。
return n*fact(n-1L)
return n*fact(n-1L)
We multiply n
times n-1
and pass it back into the recursive function because it is checking for factorials, and we want to go all the way until n
is 0 ( 6!
shouldn't yield 6*5
, it should yield 6*5*4*3*2*1
.) 我们将
n
乘以n-1
并将其传递回递归函数,因为它正在检查阶乘,因此我们要一直进行到n
为0( 6!
不应该产生6*5
,它应该产生6*5*4*3*2*1
)
Not infinite. 不是无限的。 It is, in fact, a classic example of inductive definition, which in programming translates into recursion.
实际上,它是归纳定义的经典示例,在编程中它可以转换为递归。 For it to work, there need to be two parts:
要使其正常工作,必须包含两个部分:
fact(0)
. fact(0)
做什么。 fact(n - 1)
and multiply by n
. fact(n - 1)
并乘以n
。 So... let's say you have fact(3)
. 所以...假设您有
fact(3)
。 It is not terminating, so it is 3 * fact(2)
. 它没有终止,所以是
3 * fact(2)
。 Still not terminating, so it is 3 * (2 * fact(1))
. 仍然没有终止,所以它是
3 * (2 * fact(1))
。 Still going! 仍在继续!
3 * (2 * (1 * fact(0)))
. 3 * (2 * (1 * fact(0)))
。 And there's our terminating condition, which does not call fact
any more: 3 * (2 * (1 * (1)))
. 这是我们的终止条件,不再需要
fact
: 3 * (2 * (1 * (1)))
。 So... not so infinite :) 所以...不是那么无限:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.