![](/img/trans.png)
[英]Python function that takes a positive integer n and returns the sum of the squares of all the positive integers smaller than 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
定义阶乘(n):
if n == 0:
return 1
else:
return n * factorial(n-2)
我似乎无法弄清楚这个问题。 我可以找到偶数阶乘的偶数,但我似乎无法弄清楚如何同时为奇数阶乘找到偶数。 我已经做了好几天了。 我对python非常陌生,所以任何帮助都会非常感激。 谢谢!
这应该有效!
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))
输出将是:
48
48
如您所见,等于n = 6
或n = 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.