計算機科学のブログ

ほしい物リスト

Python - gazpacho - Working with Data: Data Manipulation - function

Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly GuidePaul Barry(著)、 O’Reilly Mediaの Chapter 10.(Working with Data: Data Manipulation)、EXERCISE(469/682)の解答を求めてみる。

コード

webapp/swimclub.py

import os
import statistics

FOLDER = 'swimdata'


def read_swim_data(filename: str):
    swimmer, age, distance, stroke = filename.removesuffix('.txt').split('-')
    with open(os.path.join(FOLDER, filename)) as f:
        lines = f.readlines()
        times = lines[0].strip().split(',')
    converts = []
    for t in times:
        if ':' in t:
            minutes, rest = t.split(':')
        else:
            minutes = 0
            rest = t
        seconds, hundredths = rest.split('.')
        converts.append(
            int(minutes) * 60 * 100 + int(seconds) * 100 + int(hundredths)
        )
        average = statistics.mean(converts)
        mins_secs, hundredths = str(round(average / 100, 2)).split('.')
        mins_secs = int(mins_secs)
        minutes, seconds = divmod(mins_secs, 60)
        average = f'{minutes}:{seconds}.{hundredths}'
    return swimmer, age, distance, stroke, times, average, converts


def event_lookup(event: str):
    conversions = {
        'Free': 'freestyle',
        'Back': 'backstroke',
        'Breast': 'breaststroke',
        'Fly': 'butterfly',
        'IM': 'individual medley',
    }
    *_, distance, stroke = event.removesuffix('.txt').split('-')
    return f'{distance} {conversions[stroke]}'