Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop help
#14
(May-08-2017, 02:20 AM)jhall710 Wrote: I keep getting the same output [4, 5, 2, 6, 8] instead of [2, 4, 5, 6, 8]

here's my code

list_ = [6,8,4,5,2]
I = 0
J = 999
while I < 5:
   J = 0
   while J < 4:
       list_[J], list_[J + 1] = list_[J + 1], list_[J]  # This if statement will check values in list and then...
       J += 1
       I += 1
print(list_)

I get the output desired output keeping the IF statement....which I see you removed. The purpose of the If statement is to check the values. Your code does no checking of the values, its just random swapping, which is why you don't get the desired result. Cool  Below I have attached an example

list_ = [6,8,4,5,2]
I = 0
J = 999
while I < 5:

    J = 0
    while J < 4:
        if list_[J]> list_[J+1]:    # This if statement will check values in list and then...
            list_[J],list_[J+1] = list_[J+1],list_[J]# swap the values if the item after it has a lesser value
            J += 2                  # it should skip over the swap it just made.
           

        else:
            J += 1                     # keep moving forward 1
            I += 1                     # so the loop doesn't continue forever

print(list_)
Reply


Messages In This Thread
while loop help - by jhall710 - Apr-25-2017, 09:36 PM
RE: while loop help - by Larz60+ - Apr-26-2017, 12:07 AM
RE: while loop help - by jhall710 - Apr-27-2017, 01:15 AM
RE: while loop help - by Larz60+ - Apr-27-2017, 01:58 AM
RE: while loop help - by smbx33 - Apr-27-2017, 07:28 AM
RE: while loop help - by jhall710 - May-07-2017, 08:05 PM
RE: while loop help - by ichabod801 - May-07-2017, 09:54 PM
RE: while loop help - by jhall710 - May-08-2017, 12:28 AM
RE: while loop help - by ichabod801 - May-08-2017, 01:12 AM
RE: while loop help - by jhall710 - May-08-2017, 02:20 AM
RE: while loop help - by smbx33 - May-08-2017, 08:59 PM
RE: while loop help - by volcano63 - May-08-2017, 09:25 PM
RE: while loop help - by ichabod801 - May-08-2017, 11:57 AM
RE: while loop help - by nilamo - May-08-2017, 04:41 PM
RE: while loop help - by volcano63 - May-08-2017, 08:00 PM
RE: while loop help - by ichabod801 - May-08-2017, 09:37 PM

Forum Jump:

User Panel Messages

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