開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 16.(Classes and Functions)のExercises 16-1、2.(No. 3711)を取り組んでみる。
Exercises 16-1、2.(No. 3711)
コード(Emacs)
test
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
class Time:
pass
def increment(time, second):
time.second += second
if time.second >= 60:
time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = map(int, divmod(seconds, 60))
time.hour, time.minute = divmod(minutes, 60)
return time
def add_time(t1, t2):
assert valid_time(t1) and valid_time(t2)
seconds = time_to_int(t1) + time_to_inte(t2)
return int_to_time(seconds)
def valid_time(time):
if time.hour >= 0 and 0 <= time.minute < 60 and 0 <= time.second < 60:
return True
return False
def mul_time(time, n):
assert(valid_time(time))
return int_to_time(time_to_int(time) * n)
def average_pace(time, distance):
return mul_time(time, 1 / distance)
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
distance = 10
average = average_pace(time, distance)
print('{0:02}:{1:02}:{02}'.format(
average.hour, average.minute, average.second))
print('1.')
date = datetime.date.today()
print(date.strftime('%A'))
print('2.')
birth = input('birth day(YYYY-MM-DD): ')
birth = map(int, birth.split('-'))
birth = datetime.date(*birth)
byear = birth.year
bmonth = birth.month
bday = birth.day
tday = datetime.date.today()
print(tday)
tyear = tday.year
tmonth = tday.month
tday = tday.day
if tyear == byear:
age = 0
else:
age = tyear - byear
if bmonth < tmonth:
age -= 1
elif bmonth == tmonth:
if bday < tday:
age -= 1
print('age: {0}'.format(age))
tday = datetime.datetime.today()
if tday > datetime.datetime(tday.year, birth.month, birth.day):
birth_next = datetime.datetime(tday.year + 1, birth.month, birth.day)
else:
birth_next = datetime.datetime(tday.year, birth.month, birth.date)
t = birth_next - tday
d = t.days
h = t.seconds // (60 * 60)
m = t.seconds // 60 - h * 60
s = t.seconds - h * 60 * 60 - m * 60
print('until next birth day: {0} days, {1} hours, {2} minutes, {3} seconds'
.format(d, h, m, s))
print('3.')
b1 = datetime.date(2000, 1, 2)
b2 = datetime.date(2010, 1, 2)
b = b2 - b1
print(b2 + b)
n = 5
b1 = datetime.date(2000, 1, 2)
b2 = datetime.date(2010, 1, 2)
b = b2 - b1
print(b2 + 1 / (n - 1) * b)
入出力結果(Terminal, IPython)
$ ./sample1.py 01:11:57 1. Wednesday 2. birth day(YYYY-MM-DD): 2000-1-2 2016-10-05 age: 15 until next birth day: 88 days, 7 hours, 55 minutes, 8 seconds 3. 2020-01-03 2012-07-03 $
0 コメント:
コメントを投稿