简体   繁体   English

你如何在 python 中为阶乘创建一个函数,该阶乘是使用递归的所有小于或等于 n 的正偶数整数的乘积

[英]How do you make a function in python for a factorial that is the product of all the positive EVEN integers less than or equal to n using recursion

def factorial(n):定义阶乘(n):

if n == 0:

   return 1

else: 

   return n * factorial(n-2)

I can not seem to be able to figure this problem out.我似乎无法弄清楚这个问题。 I can find the even integers for even factorials, but I can not seem to figure out how to find even integers for odd factorials at the same time.我可以找到偶数阶乘的偶数,但我似乎无法弄清楚如何同时为奇数阶乘找到偶数。 I've been at it for days now.我已经做了好几天了。 I am extremely new to python, so any help would be very appreciative.我对python非常陌生,所以任何帮助都会非常感激。 Thanks!谢谢!

This should work!这应该有效!

def factorial(n):
    if n % 2 != 0:
        n -= 1
    return 1 if (n < 1) else n * factorial(n-2)
    
print(factorial(6))
print(factorial(7))

The output will be:输出将是:

48
48

Equals for n = 6 or n = 7 (even and odd numbers) as you can see如您所见,等于n = 6n = 7 (偶数和奇数)

factorial = lambda x: functools.reduce(lambda x, y: x*y, range(2, x+1, 2))

使用内部方法functools.reduce防止最大递归深度

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

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