Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find factorial of a list of numbers

I have a set of numbers:

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

I wish to create a function that calculates the factorial of each number in the set 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 am getting 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

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

Note: I don't wish to use the math.factorial function for this code.

like image 909
Sakshi Jain Avatar asked Dec 23 '22 13:12

Sakshi Jain


1 Answers

set fact=1 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)
like image 102
Van Peer Avatar answered Dec 28 '22 10:12

Van Peer