2014年6月21日土曜日

開発環境

Head First Python (Paul Barry(著)、 O'Reilly Media )のChapter 6(Custom data Objects: Bundling code with data)、EXERCISE, SHARPEN YOUR PENCIL(p.199)を解いてみる。

EXERCISE, SHARPEN YOUR PENCIL(p.199)

コード(BBEdit)

sample199.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

def sanitize(time_string):
    if '-' in time_string:
        spliter = '-'
    elif ':' in time_string:
        spliter = ':'
    else:
        return time_string

    (mins, secs) = time_string.split(spliter)
    return mins + '.' + secs

class Athlete:
    def __init__(self, name, dob, times):
        self.name = name
        self.dob = dob
        self.times = times
    def top3(self):
        return sorted(set(sanitize(t) for t in self.times))[:3]
    def addTime(self, time):
        self.times.append(time)
    def addTimes(self, times):
        self.times.extend(times)
        
def getCoachData(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        temp =  data.strip().split(',')
        return Athlete(temp.pop(0), temp.pop(0), temp)
    except IOError as ioerr:
        print('File error: {0}'.format(ioerr))
        return None

for filename in ['sarah2.txt', 'james2.txt', 'julie2.txt', 'mikey2.txt']:
    athlete = getCoachData(filename)
    print("{0}'s fastest times are: {1}".format(athlete.name, athlete.top3()))
    athlete.addTime('2.0')
    print("{0}'s fastest times are: {1}".format(athlete.name, athlete.top3()))
    athlete.addTimes(['1.0', '1.1', '1.2'])
    print("{0}'s fastest times are: {1}".format(athlete.name, athlete.top3()))

入出力結果(Terminal)

$ ./sample199.py
Sarah Sweeney's fastest times are: ['2.18', '2.21', '2.22']
Sarah Sweeney's fastest times are: ['2.0', '2.18', '2.21']
Sarah Sweeney's fastest times are: ['1.0', '1.1', '1.2']
James Lee's fastest times are: ['2.01', '2.16', '2.22']
James Lee's fastest times are: ['2.0', '2.01', '2.16']
James Lee's fastest times are: ['1.0', '1.1', '1.2']
Julie Jones's fastest times are: ['2.11', '2.23', '2.59']
Julie Jones's fastest times are: ['2.0', '2.11', '2.23']
Julie Jones's fastest times are: ['1.0', '1.1', '1.2']
Mikey McManus's fastest times are: ['2.22', '2.31', '2.38']
Mikey McManus's fastest times are: ['2.0', '2.22', '2.31']
Mikey McManus's fastest times are: ['1.0', '1.1', '1.2']
$

0 コメント:

コメントを投稿