Home > Enterprise >  How do I bubblesort lists of numbers within a list in python?
How do I bubblesort lists of numbers within a list in python?

Time:08-09

Say you have students and grades as your lists

students = ['tom', 'richard', 'henry']
grades = [[78, 88, 98], 
          [88, 76, 55], 
          [80, 81, 79]]

I want to print out the students with their grades sorted from high to low, but all I've done is sort the lists themselves from high to low.

def bubbleSort(scores):
    maxLength = len(scores) - 1
    while maxLength >= 0:
        index = 0
        while index <= maxLength - 1:
            if scores[index] > scores[index   1]:
                temp = scores[index]
                scores[index] = scores[index   1]
                scores[index   1] = temp
            index = index   1
        maxLength = maxLength - 1
    return scores

The output currently looks like this, switching list two and three.

tom [78, 88, 98]
richard [80, 81, 79]
henry [88, 76, 55]

How do I get it to bubblesort within the lists, not the lists themselves?

CodePudding user response:

Pass each sublist to bubbleSort rather than the top-level list.

for scores in grades:
    bubbleSort(scores)

CodePudding user response:

Use sorted function

lst=[]
for g,s in zip(grades,students):
    lst=sorted(g,reverse=True)
    print(f"{s} {lst}")
  • Related