Page 212 -
P. 212

sarah’s times


                           Code Magnets Solution


                           Let’s look at the code to implement the strategy outlined earlier. For now, let’s concentrate on
                           Sarah’s data.
                           You were to rearrange the code magnets at the bottom of the previous page to implement the list
                           processing required to extract and process Sarah’s three fastest times from Coach Kelly’s raw data.



                           def sanitize(time_string):
                               if '-' in time_string:
                                   splitter = '-'
                               elif ':' in time_string:
                                   splitter = ':'
                               else:
                                   return(time_string)
                               (mins, secs) = time_string.split(splitter)
                               return(mins + '.' + secs)

                           def get_coach_data(filename):
                               try:
                                   with open(filename) as f:
                                       data = f.readline()
                                   return(data.strip().split(','))
                               except IOError as ioerr:                        Use the function to turn
                                   print('File error: ' + str(ioerr))          Sarah’s data file into a list,
                                                                               and then assign it to the
                                   return(None)
                                                                              “sarah” variable.


                            sarah      =       get_coach_data('sarah2.txt')

                           (sarah_name, sarah_dob)         =       sarah.pop(0), sarah.pop(0)

           The “pop(0)” call   print(sarah_name +   "'s fastest times are: " +
            returns and
            removes data from          str(sorted(set([sanitize(t) for t in sarah]))[0:3]))
            the front of a
            list.. Two calls to
                                                                     A custom message within
           “pop(0)” remove                                           the call to “print()” is used
            the first two data                                       to display the results you’re
            values and assigns                                      after.
            them to the named
            variables.


           176    Chapter 6
   207   208   209   210   211   212   213   214   215   216   217