Starting from:

$25

CS515 - Assignment 1 - Solved

Writing your own factorial function 
 

 

>>>    f  r  o   m     m   a    t   h       i   m   p  o  r t factorial

>>>   factorial( 5)

 >>>  120

As shown above, we can use the factorial function from the math module. Here, you'll write your  own factorial function. First, we start with a simple function that returns the pro  duct of its two inpu ts:

def mult(x, y): 

   """Returns the product of x and y"""    return x * y 

Nothing too surprising here. Now, take a look at this: 

>>> reduce(mult, [2, 3]) 



>>> reduce(mult, [2, 3, 4]) 

24 

>>> reduce(mult, [1, 2, 3, 4]) 

24 

Notice that reduce takes two inputs: A function and a list and it applies that function to "compress" the list into a single value. In this case, it multiplied all of the values together. 

Now, write a function factorial(n) that takes a positive integer n and returns n!. 

This is "mean"... 
Finally, write a function called mean(L) that takes a list as input and returns the mean (average) value in that list. Using reduce will be handy here. You may also want to define an add function that returns the sum of two numbers. You'll need to know the number of elements in the list. This can be found using the built-in function len. For example: 

>>> len([1, 3, 5]) 



>>> len(range(1,10)) 



Here is the mean function in action: 

>>> mean([1, 2, 3]) 



>>> mean([1, 1, 1]) 

More products