简体   繁体   English

Python 2.7代码,需要说明

[英]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. 这是一个递归函数。

Line by line 逐行

Line 1: if n == 0: 第1行: 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

Line 2: return 1L 第2行: 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

Line 3: return n*fact(n-1L) 第3行: 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: 要使其正常工作,必须包含两个部分:

  • Terminating condition, that describes when the problem is simple enough that we know the answer. 终止条件,它描述问题何时足够简单以使我们知道答案。 In this case, what to do for fact(0) . 在这种情况下,为fact(0)做什么。
  • Non-terminating condition, that describes how to break down a complex problem into simpler ones. 非终止条件,它描述了如何将一个复杂的问题分解为更简单的问题。 In this case, look up 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))) . 这是我们的终止条件,不再需要fact3 * (2 * (1 * (1))) So... not so infinite :) 所以...不是那么无限:)

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

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