Brendan Levine Brendan Levine - 12 days ago 35
Python Question

I'm trying to implement a selection sort on a list of tuples

The list contains a number of tuples with the first element of the tuple being a name and the second element being a rating.

Tuple = [('Bob', 123),('Sky', 234),('Sara', 156)]
for i in range(0, len(Tuple)-1):

smallest = i

for j in range(i+1, len(Tuple)):

if Tuple[j] < Tuple[smallest]:

smallest = j

if smallest !=i:

Tuple[i], Tuple[smallest] = Tuple[smallest] , Tuple[i]
print(Tuple)


This will sort the list in alphabetical order but I want it to be sorted by rating highest to lowest.

I've tried this:

for i in range(0, len(Tuple)-1):

smallest = i[1]

for j in range(i+1, len(Tuple)):

if Tuple[j[1]] < Tuple[smallest]:

smallest = j

if smallest !=i:

Tuple[i], Tuple[smallest] = Tuple[smallest] , Tuple[i]
print(Tuple)


But I get an error saying "smallest = i[1] TypeError: 'int' object is not subscriptable'

I don't know how else to do this or how I can change it to make it work.

Note: I need to write the code myself and not use any built in functions.

Answer

With your original list,

names_ratings = [("Bob", 123), ("Sky", 234), ("Sara", 156)]   

You can use the python builtin sorted.

names_ratings_sorted = sorted(names_ratings, key=lambda tup: tup[1])

print(names_ratings_sorted)

Output:

[("Bob", 123), ("Sara", 156), ("Sky", 234)]   

Without builtins:

Using the same original list,

names_ratings = [("Bob", 123), ("Sky", 234), ("Sara", 156)] 

This works without using any built-ins.

names_ratings_sorted = []

while names_ratings:

    maximum = names_ratings[0]

    for name, rating in names_ratings:

        if rating > maximum[1]:

            maximum = (name, rating)

    name_ratings_sorted.append(maximum)
    names_ratings.remove(maximum)