rth rth -4 years ago 114
Python Question

python iterative process inside lambda function

I have a simple python function

def positiveGauss(mean,stdev):
result = -1
while result < 0:
result = mean + np.random.randn()*stdev
return result


Is it possible to do the same trick using lambda? It requires to have iterations inside lambda, but I still believe it is possible.

Answer Source
positive_gauss = lambda mean, stddev, result = -1: positive_gauss(mean, stddev, mean + np.random.randn()*stddev) if result < 0 else result 

This is a recursive function. I'll break it down -

lambda mean, stddev, result = -1:  # takes 3 parameters 
    positive_gauss(mean, stddev, mean + np.random.randn()*stddev) if result < 0 
    # ^ Your first condition, if its true call the same function modifying result
    else result # if the above one fails just return result.

Yes, as @juanpa.arrivillaga this should not be used because its losing the essence of anonymous functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download