I am taking a beginners programming class using JES which I believe is Python 2. My teacher has asked that we create an empty list and then add random numbers to it, then sort it from lowest to highest. That part I have done correctly. The extra credit is to add a nested for loop that will count the reps it takes to sort the list. This is what I have:
from random import *
def main():
# create list of 25 (this can be changed to number of your choice) random numbers from -100 to 100
# print list with message "list before shuffling"
numList = []
count = 0
while count < 15:
num = randint( -100 , 100 )
numList.append(num)
count = count + 1
printNow("the List before shuffling: " +str(numList))
n = len(numList)
add = 0
# Randomly shuffle list with items only moving if a lower number is being switched with a larger number
# do this 1000 times ( this can be changed to number of your choice)
# print list with message "list after shuffling"
for reps in range (0 , 500):
i = randrange(0, n)
j = randrange(0, n)
# extra credit, add nested for loop to count number of reps it takes to sort the list
for sort in range(0, len(numList)):
for item in range(sort+1, len(numList)):
while numList[sort] < numList[item] or add < reps:
add = add + 1
if i < j:
if numList[i] > numList[j]:
temp = numList[i]
numList[i] = numList[j]
numList[j] = temp
elif j < i:
if numList[i] < numList[j]:
temp = numList[j]
numList[j] = numList[i]
numList[i] = temp
print(" List was sorted in " + str(add) + " reps.")
printNow("The List after shuffling: " +str(numList))
My teacher says that I have too many loops in my extra credit section. I am stuck and am looking for someone to explain what I am doing wrong. I DO NOT want someone to solve it for me, but tell me what I am doing wrong.
I don't believe that is any reason for you to put a while
loop within your two-level for
loop. With two for
loops, you should be able to iterate through your list and use some other conditional-checker (hint: that you have already used in this script you've shown) to determine whether the current list element is in the right spot (for the moment - may be shuffled around later). You could look in to:
bubble sort