Python递归阶乘函数 [英] Python recursive Factorial Function

查看:115
本文介绍了Python递归阶乘函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找到了此解决方案来在python中创建 factorial() 函数,但是我在理解"为什么"有效时遇到了麻烦.

Found this solution to make a factorial() function in python, but I am having trouble with understanding 'why' it works.

函数是:

def factorial(x):
  if x <= 1:
    return 1
   else:
    return x * factorial(x-1)

我无法理解实际乘法发生在哪里?

在我看来,该函数将不断调用自身,直到达到1,然后返回1.有人可以启发我吗?我确定我缺少简单的东西.

It would seem to me, that the function would keep calling itself until it gets to 1, and returns 1. Can someone enlighten me? I'm sure I'm missing something easy.

推荐答案

编程的一般技巧是插入print语句,以帮助您了解代码运行时发生的情况.当您破坏了要修复的代码时,这特别有用,同时也有助于理解新代码.在这种情况下,请尝试运行以下命令:

A general tip for programming is to insert print statements to help you see what's happening as the code runs. This is especially useful when you have broken code that you are trying to fix but is also good for understanding new code. In this case try running the following:

def factorial(x):
    print "x", x
    if x <= 1:
        print "base case, returning 1"
        return 1
    else:
        sub_fact = factorial(x-1)
        print "factorial(x-1)", sub_fact
        result = x * sub_fact
        print "return", result
        return result

factorial(4)

这篇关于Python递归阶乘函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆