Python Forum
Thread Rating:
  • 3 Vote(s) - 2.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
3 random numbers
#1
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
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  random numbers, randint janeik 2 526 Nov-27-2023, 05:17 PM
Last Post: janeik
  find random numbers that are = to the first 2 number of a list. Frankduc 23 3,013 Apr-05-2023, 07:36 PM
Last Post: Frankduc
  List of random numbers astral_travel 17 2,533 Dec-02-2022, 10:37 PM
Last Post: deanhystad
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,429 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  output a list of random numbers 'x' columns wide adityavpratap 4 2,923 Jan-13-2020, 05:32 PM
Last Post: perfringo
  Can i prevent the random generator to generate already used numbers? MauserMan 3 2,807 Jan-05-2020, 04:44 PM
Last Post: MauserMan
  Working with Random Generated Numbers YoungGrassHopper 4 3,138 Sep-10-2019, 06:53 AM
Last Post: YoungGrassHopper
  Need to generate random numbers Gateux 8 3,866 Jul-19-2019, 03:37 PM
Last Post: Man_from_India
  Generate unique random numbers from different lists Takeshio 5 3,697 May-24-2019, 07:29 PM
Last Post: ichabod801
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,666 May-09-2019, 12:19 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020