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

How can I put the result of a calculation to be put in a list?

while seed != 1.0:
    if (seed % 2 == 0) :
        seed = seed / 2 
    else:
        seed = seed * 3 + 1

I want to put the Result of the Calculation to be put in a list.
Could I use return?
If yes how?

>Solution :

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

You can use the list method append

results = []
while seed != 1.0:
    if (seed % 2 == 0) :
        seed = seed / 2 
    else:
        seed = seed * 3 + 1
    results.append(seed)
print(results)

Output for seed = 50: [25.0, 76.0, 38.0, 19.0, 58.0, 29.0, 88.0, 44.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]

Note: the return keyword can only be used in functions and will only be useful in this example if this is in a function at the end instead of print(results)

def three_n_plus_one(seed):
    results = []
    while seed != 1.0:
        if (seed % 2 == 0) :
            seed = seed / 2 
        else:
            seed = seed * 3 + 1
        results.append(seed)
    return results

You can call the function like this:

print(three_n_plus_one(50))

It gives the same output – [25.0, 76.0, 38.0, 19.0, 58.0, 29.0, 88.0, 44.0, 22.0, 11.0, 34.0, 17.0, 52.0, 26.0, 13.0, 40.0, 20.0, 10.0, 5.0, 16.0, 8.0, 4.0, 2.0, 1.0]

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