Home > Software design >  How can I put the result of a calculation to be put in a list?
How can I put the result of a calculation to be put in a list?

Time:06-11

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?

CodePudding user response:

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]

  • Related