2017-10-06 63 views
4

列表的阶乘我有一个数字的列表:查找号码

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

+0

input_set = {1,2,3,4,5}。这不是一份清单,而是一本字典。 –

+0

[在Python中递归生成n阶乘列表]的可能副本(https://stackoverflow.com/questions/40560108/recursively-generating-a-list-of-n-factorial-in-python) –

+0

input_set = { 1,2,3,4,5}这不是一个列表或字典 –

回答

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] 
6

set​​inside for loop。

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) 
+0

啊!谢谢你这么多 –

1

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

+0

明白了! Thankyou –

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更改为列表[]而不是字典。
其次,“输入”不是您使用的关键字,您已将其命名为item。

+0

你也忘记重置事实回到1. 希望这有助于,ty –

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

还有一个内置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

其对您的变量>>其实< <你放在第一在for循环中,你的代码是好的。

什么发生在这里是进入循环,当你需要每次都做出来循环得到执行之前,您其实= 1 INITIALISE值只有一次。

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) 

希望这有助于和做小ř& d上可变范围:)