我有一组数字:
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)
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]
您需要在第二个 for 循环之前重置事实,它只是与前一个阶乘的结果相乘。
factorial()
模块中还内置了math
。
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
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
按照您的需要工作...在这里测试[https://www.tutorialspoint.com/execute_python_online.php]
这应该是你的代码。
首先,将您的 input_set 更改为列表 [] 而不是字典。
其次,“input”不是您使用过的关键字,您已将其命名为 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)
这比看起来更容易。您只需将事实/阶乘变量放入第一个循环内。这样每次循环运行时它都会重置。
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}")
谢谢,伊桑·拉尔
关于你的变量>>事实<< if you placed it in inside the first for-loop your code will work.
这里发生的事情是您的 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", item, "is", fact)
希望这对变量范围有所帮助并且做一些研发:)