求数字列表的阶乘

问题描述 投票:0回答:8

我有一组数字:

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
函数。

python for-loop math factorial
8个回答
6
投票

在 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)

2
投票
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]

1
投票

您需要在第二个 for 循环之前重置事实,它只是与前一个阶乘的结果相乘。


1
投票

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

0
投票
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。


0
投票

您忘记在迭代后重置阶乘变量。

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)

0
投票

这比看起来更容易。您只需将事实/阶乘变量放入第一个循环内。这样每次循环运行时它都会重置。

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}")

谢谢,伊桑·拉尔


0
投票

关于你的变量>>事实<< 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)

希望这对变量范围有所帮助并且做一些研发:)

© www.soinside.com 2019 - 2024. All rights reserved.