Exercise 93 *

Write an algorithm in python which transforms a list of integers L = [n1, n2, n3, ...., np] into the list of factorials: [n1! , n2! , n3!, ...., np!]

Solution

# function which calculates factorials of an integer
def facto (n):
f = 1
for i in range (1, n + 1):
f = f * i
return f

# function which transforms the list L = [n1, n2, n3, ...., np] into [n1! , n2! , n3!, ...., np!]
def list_facto (L):
# initialization of the list [n1! , n2! , n3!, ...., np!]
l_facto = []

for n in L:
l_facto.append (facto (n))

return l_facto

# Example
L = [5, 2, 1, 3, 4]
print ("List of factorials =", list_facto (L))
# The output of the program is: List of factorials = [120, 2, 1, 6, 24]
Younes Derfoufi
my-courses.net

Leave a Reply