python - 查找数字列表的阶乘

标签 python for-loop math factorial

我有一组数字:

list = {1, 2, 3, 4, 5}

我想创建一个函数来计算集合中每个数字的阶乘并打印出来。

input_set = {1, 2, 3, 4, 5}
fact = 1
for item in input_set:
    for number in range(1,item+1):
        fact = fact * number
    print ("Factorial of", item, "is", fact)

我得到的输出是:

Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 12
Factorial of 4 is 288
Factorial of 5 is 34560

这显然是错误的。 我真的很想知道我的代码有什么问题以及如何修复它。

注意:我不想对这段代码使用 math.factorial 函数。

最佳答案

在 for 循环中设置 fact=1

input_set = {1, 2, 3, 4, 5}
for item in input_set:
    fact = 1
    for number in range(1,item+1):
        fact = fact * number
        print ("Factorial of", input, "is", fact)

关于python - 查找数字列表的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598305/

相关文章:

python - PyQT 在调用其他函数之前强制更新 textEdit

Java匹配两个字符串之间的每两个序列字符

algorithm - 如何评估以质数为模的指数塔

c++ - 如何使用c++生成不相关的随机序列

c# - C#数学百分比问题

python - 如何为 "doubleclick"和 "find icon and type <some text>"的 Robot Framework 编写 Python 自定义库?

python - 有条件地循环染色体和一个数据帧中的位置到另一个数据帧中的染色体和间隔

python - 如何在 PyQT 中绘制节点和边?

c++ - 在没有字符串或数组函数的情况下迭代文本

java - 为每个循环设置值