0

I tried it with this but it gives me an error 'local variable 'l' referenced before assignment'

def likelihood(N,n,k):
    """
    Call:
        l = likelihood(N,n,k)
    Input argument:
        N: integer (array)
        n: integer (array)
        k: integer (array)
    Output argument:
        l: float (array)
    Example:
        likelihood(6,10,5)
        =>
        1.190748e-05
    """
    if isinstance(N,list): # N is array
        l = zeros(len(N)) 
        for i, I in enumerate(N):
            l[i]=exp(log_factorial(I)-log_factorial(I-k)-n*log(I))
        else: # N is scalar
            l= exp(log_factorial(N)-log_factorial(N-k)-n*log(N))
    return(l)

Where am I wrong? Or is there another way to solve it?

Veysel
  • 23
  • 5

2 Answers2

1

You are getting the error because l is defined inside the scope of the if block, so when you try and return it the function likelihood has no l variable defined.

Give l a default value, and it should be ok.

def likelihood(N,n,k):
    """ documentation trimmed"""
    l = []
    if isinstance(N,list): # N is array
        pass # rest of function here
    return l
Community
  • 1
  • 1
0

If you call the function with N not as list, then it will not go into the if clause. So l is not defined when return is reached. The actual error, though, is that the else clause is indented. This is probably what you want:

from numpy import zeros, exp, log
from scipy.special import gammaln
log_factorial = lambda z:gammaln(z+1)
def likelihood(N,n,k):
    if isinstance(N,list): # N is array
        l = zeros(len(N)) 
        for i, I in enumerate(N):
            l[i]=exp(log_factorial(I)-log_factorial(I-k)-n*log(I))
    else: # N is scalar
        l= exp(log_factorial(N)-log_factorial(N-k)-n*log(N))
    return l
likelihood([6],10,5)
likelihood(6,10,5)
Roland Puntaier
  • 3,250
  • 30
  • 35