from goody import irange, type_as_str class Date: month_dict = {1:31, 2:28, 3:31
ID: 3601735 • Letter: F
Question
from goody import irange, type_as_str
class Date:
month_dict = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
@staticmethod
def is_leap_year(year):
return (year%4 == 0 and year%100 != 0) or year%400 == 0
@staticmethod
def days_in(year,month):
return Date.month_dict[month] + (1 if month == 2 and Date.is_leap_year(year) else 0)
def __init__(self, y, m, d):
self.year = y
self.month = m
self.day = d
# Test __len__
e-->len(Date(0,1,1))-->0
e-->len(Date(0,12,31))-->365
e-->len(Date(0,3,14))-->73
e-->len(Date(1,1,1))-->366
e-->len(Date(1900,1,1))-->693961
e-->len(Date(1912,4,15))-->698448
e-->len(Date(1969,7,20))-->719363
e-->len(Date(2000,1,1))-->730485
e-->len(Date(2016,4,15))-->736434
Explanation / Answer
1.
from goody import irange,type_as_str
class Date:
month_dict = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31,11:30, 12:31}
@staticmethod
def is_leap_year(year):
return (year%4 == 0 and year%100 != 0) or year%400 == 0
@staticmethod
def days_in(year,month):
return Date.month_dict[month] + (1 if month == 2 andDate.is_leap_year(year) else 0)
def __init__(self,year,month,day):
assert type(year) is int and year >= 0,'Date.__init__:year('+str(year)+') is not positive'
assert type(month) is int and 1 <= month <= 12, 'Date.__init__:month('+str(month)+') is not int in range [1,12]'
assert type(day) is int and 1 <= day <= Date.days_in(year,month),'Date.__init__: days('+str(day)+') is not correct for month('+str(month)+')/year('+str(year)+')'
self.year= year
self.month = month
self.day= day
def __getitem__(self,index):
if type(index) is not tuple:
index =(index,)
if not all(type(i) is str and i in ('y','m','d') for i in index):
raise IndexError('Date.__getitem__: illegal argument in'+str(index))
answer = tuple(self.year if i=='y' else self.month if i=='m' elseself.day for i in index)
if len(answer)==1:
answer = answer[0]
return answer
def __repr__(self):
return 'Date('+','.join(str(part) for part in self['y','m','d'])+')'
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.