Let's consider the general problem of a race involving any number of snails. Malek is considering diversifying into amoeba racing, so there might be thousands of competitors in a race. So let's not limit the number of competitors in the program.
Also, to make it possible to use cheaper labor for production runs, let's write a general-purpose script that will read a file with the results for each race, so a relatively less skilled person can prepare that file, and then run a script that will review the results.
We'll use a very simple text file format to encode the race results. Here's an example file for that first race between Judy and Kyle:
87.3 Judy 96.6 Kyle
And here is a script that will process that file and
report on the winning time.
The script is called snailist.py.
First, reads a race results file named results and stores the times into a list.
The .split() method is used to break
each line into parts, with the first part containing the
elapsed time.
#!/usr/local/bin/python
#================================================================
# snailist.py: First snail racing results script.
#----------------------------------------------------------------
#--
# Create an empty list to hold the finish times.
#--
timeList = []
#--
# Open the file containing the results.
#--
resultsFile = open ( 'results' )
#--
# Go through the lines of that file, storing each finish time.
#--
for resultsLine in resultsFile:
#--
# Create a list of the fields in the line, e.g., ['87.3', 'Judy\n'].
#--
fieldList = resultsLine.split()
#--
# Convert the finish time into a float and append it to timeList.
#--
timeList.append ( float ( fieldList[0] ) )
At this point, timeList is a list of float values. We use the .sort()
method to sort the list into ascending order, so that the
winning time will be in the first element.
#-- # Sort timeList into ascending order, then set 'winningTime' to # the best time. #-- timeList.sort() print "The winning time is", timeList[0]
Try building the results file and
the script yourself to verify that they work. Try some
cases where there are ties.
This script is fine as far as it goes. However, there is one major drawback: it doesn't tell you who won!