Sort the array before displaying the results

The array is storing the scores in the order they were read from the file. However, you still need to sort them so that the highest scores appear first.

You could sort the array by comparing each of the elements with each of the other elements, and then swap any that are in the wrong order.

That looks complicated. Aren't we doing all this to make the code simpler and easier to maintain? I wonder if the array has any built— in methods that might help... ?

Arrays in Python have a whole host of methods that make many tasks easier.

Let's see which ones might help.

'V By closely examining the array of boxes, you can sort them by arranging the boxes in biggest-to-smallest order.

These are some of the methods that come built into every array. See if you can match up the descriptions with the method names. Draw in the missing connecting lines. We've done one for you to get you started.

Method

What the method does count() extend() index () insert () pop () remove() reverse() sort()

Sorts the array into a specified order (low to high) Removes and returns the last array item Adds an item at any index location Looks for an item and returns its index value Reverses the order of the array Tells you how many times a value is in the array Adds a list of items to an array Removes and returns the first array item

Can you work out which two methods you need to employ to allow you to sort the data in the order that you need?

sort then reverse

These are some of the methods that come built into every array. You were to match up the descriptions with the method names:

Method

What the method does

Sorts the array into a specified order (low to high)

Removes and returns the last array item

Adds an item at any index location

Looks for an item and returns its index value

Reverses the order of the array

Tells you how many times a value is in the array

Adds a list of items to an array

Removes and returns the first array item

You were to work out which two methods you needed to employ to allow you to sort the data in the order that you needed.

The sort () and reverse () methods look the most useful. You need to use reverse () after you sort () the data, because the default ordering used by sort () is lowest-to-highest, the opposite of what you need.

Was this article helpful?

0 0

Post a comment