@RR
2017-06-19T02:50:59.000000Z
字数 1601
阅读 156
kata
本文固定链接 https://www.zybuluo.com/RR/note/785947
实现一个datetime类。
days_to_other 函数计算两个日期之间的天数。返回负数表示日期再之前。
date_after_days 计算多少日以后的日期是那一天,days是负数的话,就是往前计算日期。
MyDateTime类的一些基本函数已经实现好了,并且提供了一个test_random函数,可以试试看自己的代码能获得多少的测试通过率。
from datetime import datefrom datetime import timedeltaimport randomclass MyDateTime(object):def __init__(self, y, m, d):self.year = yself.month = mself.day = ddef days_to_other(self, other):return 0def date_after_days(self, days):return selfdef __add__(self, days):return self.date_after_days(days)def __sub__(self, other):return self.days_to_other(other)def __eq__(self, other):return [self.year, self.month, self.day] == [other.year, other.month, other.day]def __str__(self):return "%d-%d-%d" % (self.year, self.month, self.day)def __repr__(self):return "%d-%d-%d" % (self.year, self.month, self.day)def test(days):delta = (days[1] - days[0]).daysday0 = MyDateTime(days[0].year,days[0].month,days[0].day)day1 = MyDateTime(days[1].year, days[1].month, days[1].day)day1_actual = day0.date_after_days(delta)delta_actual = day1.days_to_other(day0)result = Trueif delta != delta_actual:print("Expected {!s} - {!s} is {:d}, actual is {:d}".format(day1, day0, delta, delta_actual))result = Falseif day1 != day1_actual:print("Expected {!s} + {:d} is {!s}, actual is {!s}".format(day0, delta, day1, day1_actual))result = Falsereturn resultdef test_random():first_day = date(1, 1, 1)last_day = date(2017,12,31)delta = last_day - first_dayall_days = [first_day + timedelta(n) for n in range(0,delta.days)]total = 1024 * 10result = [ test(random.sample(all_days,2)) for i in range (0,total)]pass_cnt = sum([1 for i in result if i])print ("Test pass rate is {:%}".format(pass_cnt/float(total)))if __name__ == "__main__":test_random()