难以想出解决办法的:
不仅仅是一个解决方案,更希望有一个有暗示和解释的答案。
def falling(n, k):
"""Compute the falling factorial of N to depth K.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
fact = n
i = 0
while i <= k:
fact = fact * fact - 1
i += 1
n -= 1
return fact发布于 2020-08-21 17:57:44
def falling(n, k):
"""Compute the falling factorial of N to depth K.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
if k == 0:
return 1
return_value = 1
counter = 0
while counter < k:
return_value = return_value * (n-counter)
counter += 1
return return_value忽略k=0,您必须将以n开头,以n结尾的k数相乘。上面的循环k次,因为我将从0开始增加1,你可以简单地从n中减去它,得到下一个要乘的数字。
编辑:确保k=0总是通过提前返回来返回1
Edit2:删除内置的范围函数
Edit3:一定要走得很深
发布于 2020-08-21 17:58:57
由于您不需要解决方案,而是想知道代码失败的原因,所以我将给您一些提示
逻辑是错误的,这就是为什么
发布于 2022-09-11 11:17:07
首先,您需要生成数字才能将乘法应用于
例如# 6 * 5 * 4,我们通过使用
range(n, k, -1) => g for (n,k) = (6,3)为6,5,4
然后用reduce积累项目产品清单。
def falling(n, k):
return reduce(lambda x, y: x * y, list(range(n, k, -1)))
# more readable
```python坠落(n,k):
from operator import mulreturn reduce(mul, list(range(n, k, -1)))`lambda x, y: x * y` => just get the product of two number
in python 3.8+
you would use `math.prod()`
```javascriptfactorial_with_depth(n,k):
"""Compute the falling factorial of n to depth k."""from math import prod # python 3.8+return prod(range(n, k, -1))https://stackoverflow.com/questions/63527742
复制相似问题