# Map, lists and generators – Error: name 'factorial' is not defined

## Question:

I am trying to do some Bayesian analysis but I keep running into a problem with a generator and map. Here is what I have tried so far:

``````import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
%matplotlib inline
``````

Likelihood function: n = ad impressions (400000), x = ad clicks (3700), and theta the proposed probability of success.

Here is the likelihood function:

``````def likelihood(theta, n, x):
return(factorial(n) / (factorial(x) * factorial(n-x)))*(theta**x)*((1-theta)**(n-x))
``````

All possible click-through rates – as a list:

``````possible_theta_values = list(map(lambda x:x/100., range(100)))
``````

Then all possible click-through rates:

``````likelihoods = list(map(lambda theta: likelihood(theta, n, x), possible_theta_values))
``````

And here I get this error: name’factorial is not defined.
If I remove the list from the above function, it runs without error, but then when I try to visualise the results:

``````m1e = possible_theta_values[np.argmax(likelihoods)]

f, ax = plt.subplots(1)
ax.plot(possible_theta_values, likelihoods)
ax.axvline(mle, linestyle = "--")
ax.set_xlabel("Theta")
ax.set_ylabel("Likelihood")
ax.grid()
ax.set_title("Likelihood of Theta for QTR Q3 Campaign")
plt.show();
``````

I get another error: matplotlib does not support generators as input

## Answers:

Either:

``````from math import factorial
``````

or

``````def likelihood(theta, n, x):
return(math.factorial(n) / (math.factorial(x) * math.factorial(n-x)))*(theta**x)*((1-theta)**(n-x))
``````

Would solve the fact that it can’t find factorial.

If you really wanted to, you could define your own factorial function:

``````def likelihood(theta, n, x):
factorial = lambda x : x and x * factorial(x-1) or 1
return(factorial(n) / (factorial(x) * factorial(n-x)))*(theta**x)*((1-theta)**(n-x))

``````
``````from math import factorial

[n for n in range(5*24) if str(factorial(n)).count("0")==23]

>>> [66, 72, 74]
``````
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.