0

Currently I have a list, which represent the student with their test scores a = [['May', 81], ['Jack', 91], ['Mike', 52], ['Jeremy', 58], ['Mark', 71],['Sam',81],['Brian',61],['Yan',71]]

I wish to use selection sort to sort the scores first then the student name in alphabetic order.

I am a beginner and only know how to sort a normal list like

a = [1,64,23,13]

will give: a = [1,13,23,64]

My selection sort code is here:

def sort(a):
    for i in range(len(a)):
        min_item = min(a[i:])
        index = a.index(min_item)
        a[i],a[index] = a[index],a[i]
    print(a)

How can i sort the scores first then the name?

Jonnie
  • 45
  • 4

3 Answers3

1

The function min can be use in conjunction with a custom key:

def selection_sort(lst):
    for i in range(len(lst)):
        min_item = min(lst[i:], key=lambda x: (x[1], x[0]))
        index = lst.index(min_item)
        lst[i], lst[index] = lst[index], lst[i]
    print(lst)

a = [['Brian', 61], ['Jack', 91], ['Jeremy', 58], ['Mark', 71], ['May', 81], ['Mike', 52], ['Sam', 81], ['Yan', 71]]

selection_sort(a)

Output

[['Mike', 52], ['Jeremy', 58], ['Brian', 61], ['Mark', 71], ['Yan', 71], ['May', 81], ['Sam', 81], ['Jack', 91]]

The key transforms each element of lst in a tuple where the first element is the score, and the second element is the name. Note that the above solution assumes you want the lowest scores first.

Further

  1. How does tuple comparison work in Python?

As a side note, the complexity of selection sort is O(n^2), it will be best if you use the built in .sort method, complexity O(nlogn). Example of usage:

a.sort(key=lambda x: (x[1], x[0]))
print(a)

Output

[['Mike', 52], ['Jeremy', 58], ['Brian', 61], ['Mark', 71], ['Yan', 71], ['May', 81], ['Sam', 81], ['Jack', 91]]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

If you want to sort by scores first, names second, you can using itemgetter - this will be faster than using lambda and avoids using python function call

from operator import itemgetter
sorted(a, key=itemgetter(1,0))

which will result in:

 [['Mike', 52],
 ['Jeremy', 58],
 ['Brian', 61],
 ['Mark', 71],
 ['Yan', 71],
 ['May', 81],
 ['Sam', 81],
 ['Jack', 91]]
Gasanov
  • 2,839
  • 1
  • 9
  • 21
1

You can use numpy:

import numpy as np
a = [['Brian', 61], ['Jack', 91], ['Jeremy', 58], ['Mark', 71], ['May', 81], ['Mike', 52], ['Sam', 81], ['Yan', 71]]
a = np.array(a)
a[a[:,1].argsort()]