Find the factorial of the list of numbers

I have a list of numbers:

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

I want to create a function that calculates the factorial of each number in a list and prints it.

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)

The output I get is:

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

This is obviously wrong. I would really like to know what is wrong with my code and how to fix it.

Note. I do not want to use a function math.factorialfor this code.

+4
source share
7 answers

set fact=1inside the 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)
+6
source
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]
+2
source

reset 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
+1
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 [], .
-, "" , , .

0

reset .

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

→ fact < < , .

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

hope this helps and a little R&D in the scope of the variable :)

0
source

Source: https://habr.com/ru/post/1687001/


All Articles