[关闭]
@RR 2017-06-19T02:50:59.000000Z 字数 1601 阅读 156

DateTime

kata


本文固定链接 https://www.zybuluo.com/RR/note/785947

实现一个datetime类。
days_to_other 函数计算两个日期之间的天数。返回负数表示日期再之前。
date_after_days 计算多少日以后的日期是那一天,days是负数的话,就是往前计算日期。
MyDateTime类的一些基本函数已经实现好了,并且提供了一个test_random函数,可以试试看自己的代码能获得多少的测试通过率。

  1. from datetime import date
  2. from datetime import timedelta
  3. import random
  4. class MyDateTime(object):
  5. def __init__(self, y, m, d):
  6. self.year = y
  7. self.month = m
  8. self.day = d
  9. def days_to_other(self, other):
  10. return 0
  11. def date_after_days(self, days):
  12. return self
  13. def __add__(self, days):
  14. return self.date_after_days(days)
  15. def __sub__(self, other):
  16. return self.days_to_other(other)
  17. def __eq__(self, other):
  18. return [self.year, self.month, self.day] == [other.year, other.month, other.day]
  19. def __str__(self):
  20. return "%d-%d-%d" % (self.year, self.month, self.day)
  21. def __repr__(self):
  22. return "%d-%d-%d" % (self.year, self.month, self.day)
  23. def test(days):
  24. delta = (days[1] - days[0]).days
  25. day0 = MyDateTime(days[0].year,days[0].month,days[0].day)
  26. day1 = MyDateTime(days[1].year, days[1].month, days[1].day)
  27. day1_actual = day0.date_after_days(delta)
  28. delta_actual = day1.days_to_other(day0)
  29. result = True
  30. if delta != delta_actual:
  31. print("Expected {!s} - {!s} is {:d}, actual is {:d}".format(day1, day0, delta, delta_actual))
  32. result = False
  33. if day1 != day1_actual:
  34. print("Expected {!s} + {:d} is {!s}, actual is {!s}".format(day0, delta, day1, day1_actual))
  35. result = False
  36. return result
  37. def test_random():
  38. first_day = date(1, 1, 1)
  39. last_day = date(2017,12,31)
  40. delta = last_day - first_day
  41. all_days = [first_day + timedelta(n) for n in range(0,delta.days)]
  42. total = 1024 * 10
  43. result = [ test(random.sample(all_days,2)) for i in range (0,total)]
  44. pass_cnt = sum([1 for i in result if i])
  45. print ("Test pass rate is {:%}".format(pass_cnt/float(total)))
  46. if __name__ == "__main__":
  47. test_random()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注