Sort the scores from highest to lowest

You now need to add the two method calls into your code that will sort the array. The lines need to go between the code that reads the data into the list and before the code that displays the first three elements.

The array starts off m a random order. It s Vsorted-"

The array starts off m a random order. It s Vsorted-"

Here is the existing program. Add in the missing code that sorts the data, highest-to-lowest.

result_f = open("results.txt") for line in result_f:

(name, score) = line.split() scores.append(float(score)) Put the extra result f.close()

print("The top scores were:") print(scores[0]) print(scores[1]) print(scores[2])

all sorted out

Here is the existing program. You were to add in the missing code that sorts the data, highest-to-lowest.

result_f = open("results.txt") for line in result_f:

(name, score) = line.split() scores.append(float(score)) result_f .close () At this point in the Code, the array is in memory but it's not in the order you need. It's unsorted.

sCores.sortO

i=- These two method calls will sort sCorĀ«.reW) r- the data into the required order.

print("The top scores were:") print(scores[0])

print (scores [1] ) Now that the array is sorted, the first print (scores [2]) three elements contain the high scores.

After the call to sortO and veverseO, the array is sorted in the order you need-

Geek Bits

It was very simple to sort an array of data using just two lines of code. But it turns out you can do even better than that if you use an option with the sort () method. Instead of using these two lines:

scores.sort() scores.reverse()

you could have used just one, which gives the same result: scores.sort(reverse = True)

Was this article helpful?

0 0

Post a comment