w3resource

Python: Factorial of a number using itertools module


20. Factorial using Itertools

Write a Python program to find the factorial of a number using the itertools module.

Sample Solution:

Python Code:

import itertools as it
import operator as op

def factorials_nums(n):
    result = list(it.accumulate(it.chain([1], range(1, 1 + n)), op.mul))
    return result;
    
 
print("Factorials of 5 :", factorials_nums(5))
print("Factorials of 9 :", factorials_nums(9))

Sample Output:

Factorials of 5 : [1, 1, 2, 6, 24, 120]
Factorials of 9 : [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]

For more Practice: Solve these Related Problems:

  • Write a Python program to compute the factorial of a number using itertools.accumulate over a range of numbers.
  • Write a Python program to generate a sequence of partial factorials for a given number using itertools.accumulate and then return the final value.
  • Write a Python program to calculate the factorial of a number and then use map to convert the digits of the result into a list of integers.
  • Write a Python program to compute factorials for a list of numbers using itertools and then filter out those that exceed a specified limit.

Go to:


Previous: Write a Python program which iterates the integers from 1 to a given number and print "Fizz" for multiples of three, print "Buzz" for multiples of five, print "FizzBuzz" for multiples of both three and five using itertools module.
Next: Write a Python program to find the years where 25th of December be a Sunday between 2000 and 2150.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.