Python Forum
3 random numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: 3 random numbers (/thread-15368.html)



3 random numbers - MrGoat - Jan-15-2019

So I was given this question : Pick any 3 random ascending numbers and write out a loop function that prints out all 3 numbers. This was the code and solution presented to me. Can anyone understand it and explain it to me please ? I have looked at it but cannot see how it was derived and why the correct solution was printed. Thanks alot !

# any 3 ascending numbers , counter must start at 0. 
# 400 467 851
i = 0
x = 400
while x < 852:
    print(x)
    if i > 0:
        x = x + ((i + 4) * 67) + (i * 49)
    else:
        x = x + 67
    i = i + 1



RE: 3 random numbers - Larz60+ - Jan-15-2019

line 5: everything below x = 400 will be executed until x >= 852
on 1st iteration 1 = 0 and x = 400, so while loop is executed
6 of course prints value of x (400)
line 7 says if i > 0 execute line 8 otherwise execute line 10 -- 1st iteration is 0, so else gets executed
line 10: x = x + 67 -- so x becomes 467
line 11 increments i by 1 -- i becomes 1

--- back to line 5 -- x is 467 so still less than 852
line 6 print x = 467
line 7 this time i is greater than 0, so execute line 8
line 8 can be broken down:
x = 467 = ((i + 4) * 67) = x + (4 * 67) = 467 + 268 = 755
x = 755 + (i * 49) = 755 + (1 * 49) = 755 + 49 = 804

repeat one more cycle (x < 852) for final results