Python - List of Files: Functions, Modules and Files - return statement 1
Head First Python: A Learner’s Guide to the Fundamentals of Python Programming, A Brain-Friendly Guide、 Paul Barry(著)、 O’Reilly Mediaの Chapter 4.(List of Files: Functions, Modules & Files)、SHARPEN YOUR PENCIL(206/682)の解答を求めてみる。
Jupyter(コード、入出力結果)
Times.ipynb
import swimclub
swimclub.read_swim_data('Darius-13-100m-Fly.txt')
('Darius',
'13',
'100m',
'Fly',
['1:27.95', '1:21.07', '1:30.96', '1:23.22', '1:27.95', '1:28.30'],
'1:26.58')
コード
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:
minutes, rest = t.split(':')
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 = mins_secs // 60
seconds = mins_secs - minutes * 60
average = str(minutes) + ':' + str(seconds) + '.' + hundredths
return swimmer, age, distance, stroke, times, average