2014年6月18日水曜日

開発環境

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

EXERCISE SOLUTION(p.181)

コード(BBEdit)

sample181.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

def getCoachData(filename):
    try:
        with open(filename) as f:
            data = f.readline()
        return data.strip().split(',')
    except IOError as ioerr:
        print('File error: {0}'.format(ioerr))
        return None

sarah = getCoachData('sarah2.txt')
sarah_data = {'name':sarah.pop(0), 'dob':sarah.pop(0),
              'times':sorted(set(sanitize(t) for t in sarah))}

print("{0}'s fastest times are: {1}".format(
    sarah_data['name'], sarah_data['times'][:3]))

入出力結果(Terminal)

$ ./sample181.py
Sarah Sweeney's fastest times are: ['2.18', '2.21', '2.22']
$

0 コメント:

コメントを投稿