w3resource

Python: Factorial of a number using itertools module

Python Itertools: Exercise-20 with Solution

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]

Python Code Editor:


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

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.

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.

Python: Tips of the Day

Inverts a dictionary with non-unique hashable values:

Example:

def tips_collect_dictionary(obj):
  inv_obj = {}
  for key, value in obj.items():
    inv_obj.setdefault(value, list()).append(key)
  return inv_obj
ages = {
  "Owen": 25,
  "Jhon": 25,
  "Pepe": 15,
}
print(tips_collect_dictionary(ages))

Output:

{25: ['Owen', 'Jhon'], 15: ['Pepe']}

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook