递归阶乘函数

发布于 2024-10-08 08:37:43 字数 549 浏览 0 评论 0原文

如何将这两个函数组合成一个递归函数以获得以下结果:

factorial(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

这是我的阶乘函数的当前代码:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       return n * factorial(n - 1)  # recursive call


def fact(n):
   for i in range(1, n+1 ):
       print "%2d! = %d" % (i, factorial(i))

并且该代码产生的输出如下:

fact(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

如您所见,执行这两个函数给了我正确的答案,但我只是想将这两个函数简化为单个递归函数。

How can I combine these two functions into one recursive function to have this result:

factorial(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

This is the current code for my factorial function:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       return n * factorial(n - 1)  # recursive call


def fact(n):
   for i in range(1, n+1 ):
       print "%2d! = %d" % (i, factorial(i))

and the output that this code produces is the following:

fact(6)

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

As you see, the execution of these two functions gives me correct answers, but I just wanted to simplify the two functions to a single recursive function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

最丧也最甜 2024-10-15 08:37:43

我们可以将这两个函数组合成这个单个递归函数:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       returnNumber = n * factorial(n - 1)  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber

We can combine the two functions to this single recursive function:

def factorial(n):
   if n < 1:   # base case
       return 1
   else:
       returnNumber = n * factorial(n - 1)  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber
獨角戲 2024-10-15 08:37:43

2行代码:

def fac(n):
    return 1 if (n < 1) else n * fac(n-1)

测试一下:

print fac(4)

结果:

24

2 lines of code:

def fac(n):
    return 1 if (n < 1) else n * fac(n-1)

Test it:

print fac(4)

Result:

24
怼怹恏 2024-10-15 08:37:43
def factorial(n):
    result = 1 if n <= 1 else n * factorial(n - 1)
    print '%d! = %d' % (n, result)
    return result
def factorial(n):
    result = 1 if n <= 1 else n * factorial(n - 1)
    print '%d! = %d' % (n, result)
    return result
貪欢 2024-10-15 08:37:43

简短的:

def fac(n):
    if n == 0:
        return 1
    else:
        return n * fac(n-1)
print fac(0)

a short one:

def fac(n):
    if n == 0:
        return 1
    else:
        return n * fac(n-1)
print fac(0)
少女情怀诗 2024-10-15 08:37:43

试试这个:

def factorial( n ):
   if n <1:   # base case
       print "%2d! = %d" % (n, n)
       return 1
   else:
       temp = factorial( n - 1 )
       print "%2d! = %d" % (n, n*temp)
       return n * temp  # recursive call

我注意到的一件事是,对于 n<1,您将返回“1”,这意味着即使对于负数,您的函数也会返回 1。您可能想解决这个问题。

try this:

def factorial( n ):
   if n <1:   # base case
       print "%2d! = %d" % (n, n)
       return 1
   else:
       temp = factorial( n - 1 )
       print "%2d! = %d" % (n, n*temp)
       return n * temp  # recursive call

One thing I noticed is that you are returning '1' for n<1, that means your function will return 1 even for negative numbers. You may want to fix that.

成熟稳重的好男人 2024-10-15 08:37:43

我没有使用Python的经验,但是像这样的东西?

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       f = n * factorial( n - 1 )  # recursive call
       print "%2d! = %d" % ( n, f )
       return f

I've no experience with Python, but something like this?

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       f = n * factorial( n - 1 )  # recursive call
       print "%2d! = %d" % ( n, f )
       return f
作死小能手 2024-10-15 08:37:43

这是作业吗?

def traced_factorial(n):
  def factorial(n):
    if n <= 1:
      return 1
    return n * factorial(n - 1)
  for i in range(1, n + 1):
    print '%2d! = %d' %(i, factorial(i))

请阅读 PEP227 了解更多详细信息。缺点是 Python 允许您在函数内定义函数。

Is this homework by any chance?

def traced_factorial(n):
  def factorial(n):
    if n <= 1:
      return 1
    return n * factorial(n - 1)
  for i in range(1, n + 1):
    print '%2d! = %d' %(i, factorial(i))

Give PEP227 a read for more details. The short of it is that Python lets you define functions within functions.

江挽川 2024-10-15 08:37:43
fac = lambda x: 1 if x == 0 else x * fac(x - 1)
fac = lambda x: 1 if x == 0 else x * fac(x - 1)
画▽骨i 2024-10-15 08:37:43

再来一张

def fact(x):
    if x in {0, 1}:
        return 1
    else:
        return x * fact(x-1)

for x in range(0,10):
    print '%d! = %d' %(x, fact(x))

One more

def fact(x):
    if x in {0, 1}:
        return 1
    else:
        return x * fact(x-1)

for x in range(0,10):
    print '%d! = %d' %(x, fact(x))
剪不断理还乱 2024-10-15 08:37:43

并首次使用递归和 while 循环计算阶乘。

def factorial(n):
    while  n >= 1:
        return n * factorial(n - 1)
    return 1

虽然 TrebledJ 在关于使用 if 的注释中写的选项更好。因为 while 循环比 if 执行更多操作(SETUP_LOOP、POP_BLOCK)。该功能较慢。

def factorial(n):
    if  n >= 1:
        return n * factorial(n - 1)
    return 1

timeit -n 10000 -r 10

  • while 每个循环 836 µs ± 11.8 µs
  • if 每个循环 787 µs ± 7.22 µs

And for the first time calculate the factorial using recursive and the while loop.

def factorial(n):
    while  n >= 1:
        return n * factorial(n - 1)
    return 1

Although the option that TrebledJ wrote in the comments about using if is better. Because while loop performs more operations (SETUP_LOOP, POP_BLOCK) than if. The function is slower.

def factorial(n):
    if  n >= 1:
        return n * factorial(n - 1)
    return 1

timeit -n 10000 -r 10

  • while 836 µs ± 11.8 µs per loop
  • if 787 µs ± 7.22 µs per loop
抠脚大汉 2024-10-15 08:37:43

可以使用这4行代码...

   def factorial(n):
        f = lambda n: n * f(n - 1) if n > 1 else 1

        for x in range(n):
            print('{}! = {}'.format(x + 1, factorial(x + 1)))

Can use these 4 lines of code...

   def factorial(n):
        f = lambda n: n * f(n - 1) if n > 1 else 1

        for x in range(n):
            print('{}! = {}'.format(x + 1, factorial(x + 1)))
少女情怀诗 2024-10-15 08:37:43

我真的不知道负数的阶乘,但这适用于所有 n >= 0:

def factorial(n):
    if n >= 0:
        if n == 1 or n == 0:
            return 1
        else:
            n = n * factorial(n-1)
            return n

    return 'error'

I don't really know the factorial of negative numbers, but this will work with all n >= 0:

def factorial(n):
    if n >= 0:
        if n == 1 or n == 0:
            return 1
        else:
            n = n * factorial(n-1)
            return n

    return 'error'
冰魂雪魄 2024-10-15 08:37:43

在 Python 3.8 中,您可以尝试阶乘函数本身。

import math
n=int(input())
print(math.factorial(n))

例如:

Input: 5

Output:120

In Python 3.8 you can try factorial function itself.

import math
n=int(input())
print(math.factorial(n))

For example:

Input: 5

Output:120
十雾 2024-10-15 08:37:43

递归函数中总是存在某种循环和一些停止循环的停止代码:

public int recursivefactorial(int number)
{
    if(number==1)
        return 1;
    else
        return recursivefactorial(number-1)*number;
}

如您所见,满足 if 条件会导致实际结束“循环”的代码,这是递归函数中最重要的部分。相反,条件的 else 部分会导致再次调用 recursivefactorial 函数,这实际上是一种循环。

There is always some kind of a loop in recursive functions and some stoping codes which stop the loop:

public int recursivefactorial(int number)
{
    if(number==1)
        return 1;
    else
        return recursivefactorial(number-1)*number;
}

As you can see the fulfilling the if condition leads to the code that actually ends the "loop" and this is the most important part of a recursive function. In contrast, the else part of the condition leads to calling recursivefactorial function once again which is effectively a kind of loop.

黑白记忆 2024-10-15 08:37:43

再来一张 =)

#FAC calculation

def fakulteta(x):
    if x!=1:
         return x*fakulteta(x-1)
    return 1


print (fakulteta(12))

One more =)

#FAC calculation

def fakulteta(x):
    if x!=1:
         return x*fakulteta(x-1)
    return 1


print (fakulteta(12))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文