Python 求一系列数字的阶乘
我有一组数字:Python 求一系列数字的阶乘,python,for-loop,math,factorial,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
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
函数 设置fact=1
内部for循环
def factorial(n):
fact = 1
for factor in range(1, n + 1):
fact *= factor
return fact
>>> my_list = [1, 2, 3, 4, 5]
>>> my_factorials = [factorial(x) for x in my_list]
>>> my_factorials
[1, 2, 6, 24, 120]
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)
您需要在第二个for循环之前重置事实,它只是与前一个阶乘的结果相乘
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
fact = 1
根据您的需要工作。。。在这里测试[
这应该是你的代码。
首先,将输入设置更改为列表[],而不是字典。其次,“输入”不是您使用过的关键字,您已将其命名为item。您忘记在迭代后重置阶乘变量
input_set = {1, 2, 3, 4, 5}
for item in input_set:
fact = 1
for number in range(1,item+1):
print fact
print number
fact = fact * number
print ("Factorial of", item, "is", fact)
math
模块中还有一个内置的factorial()
from math import factorial
def factorialize(nums):
""" Return factorials of a list of numbers. """
return [factorial(num) for num in nums]
numbers = [1, 2, 3, 4, 5]
for index, fact in enumerate(factorialize(numbers)):
print("Factorial of", numbers[index], "is", fact)
它打印:
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
这是关于你的变量的>>事实这比看起来容易。你只需要将事实/阶乘变量放在第一个循环中。这样每次循环运行时它都会被重置
for number in [1, 2, 3, 4, 5]:
factorial = 1
for i in range(1, number + 1):
factorial *= i
print(f"Factorial of {number} is {factorial}")
谢谢,Ethan Lalinput_set={1,2,3,4,5}。这不是一个列表,而是一个字典。input_set={1,2,3,4,5}可能重复这不是一个列表或字典,但你是对的!你只是把变量放错了位置,只是在评论中解释的时间太长了,所以发布了答案。检查一下。你还忘了将事实重置为1。希望这有帮助,泰阿!非常感谢!谢谢
for number in [1, 2, 3, 4, 5]:
factorial = 1
for i in range(1, number + 1):
factorial *= i
print(f"Factorial of {number} is {factorial}")