I have function, where I wish to get its output, and pass this output to the same function again, while a particular condition holds true. Then collect results in a list.
I have tried to break this down into the following representative problem, where I want to generate a random number (between 0 and 1) using random(), repeat this until random() generates a value greater than 0.5. All values to be stored in a list
from random import random
my_ls = []
def my_func():
a=random()
while a > 0.5:
my_ls.append(my_func())
I get an empty list.
>Solution :
You want to generate a list of random floating point numbers. In the end, all randomly generated floats in the list will be between zero and 0.5. The way you want to achieve this is by generating random numbers between zero and one, and as soon as you generate a number that’s larger than 0.5, you want to stop generating/appending new numbers. Is this correct?
from random import random
def get_floats():
floats = []
while True:
current_float = random()
if current_float > 0.5:
break
floats.append(current_float)
return floats
print(get_floats())
Which can be re-written as:
from random import random
def get_floats():
floats = []
while (current_float := random()) < 0.5:
floats.append(current_float)
return floats
print(get_floats())