Page 220 -
P. 220
code review
Head First
Code Review
The Head First Code Review Team has been at it It’s great to see
again: they’ve scribbled all over your code. Some you taking some of our
of their comments are confirmations; others are suggestions on board.
suggestions. Like all code reviews, these comments Here are a few more...
are an attempt to improve the quality of your code.
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() Rather than building the dictionary as you go
return(data.strip().split(',')) along, why not do it all in one go? In fact, in
except IOError as ioerr: this situation, it might even make sense to do
print('File error: ' + str(ioerr)) this processing within the get_coach_data()
return(None)
function and have the function return a
sarah = get_coach_data('sarah2.txt') populated dictionary as opposed to a list.
Then, all you need to do is create the
sarah_data = {}
sarah_data['Name'] = sarah.pop(0) dictionary from the data file using an
sarah_data['DOB'] = sarah.pop(0) appropriate function call, right?
sarah_data['Times'] = sarah
print(sarah_data['Name'] + "'s fastest times are: " +
str(sorted(set([sanitize(t) for t in sarah_data['Times']]))[0:3]))
You might want to consider moving this code into the get_coach_data() function, too, because doing so
would rather nicely abstract away these processing details. But whether you do or not is up to you. It’s
your code, after all!
184 Chapter 6