Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pass output of a function as an argument to next function, and loop while a condition is true

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading