Page 175 -
P. 175

all sorted out




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

                              scores = []
                              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.sort()
                              scores.reverse()   These two method calls will sort
                                                  the data into the required order.



                              print("The top scores were:")
                              print(scores[0])
                                                     Now that the array is sorted, the first
                              print(scores[1])
                                                     three elements contain the high scores.
                              print(scores[2])


            After the call to sort() and
            reverse(), the array is sorted
            in the order you need.


                            boxes




                                     0                     1                       2                     3





                       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)


           140    Chapter 4
   170   171   172   173   174   175   176   177   178   179   180