我试图检查日期是否有效,但我一直试图找出闰年日期是否有效。我不断收到这条消息,上面写着:LAST RUN on 02/11/2018, 12:49:03 你的函数说 29/2/1754 是有效的,但它是无效的。我知道这不是闰年。每当一年不是闰年时,我都试图在 validDate 函数中返回一个 False 值。您可以给我的任何信息,将不胜感激。谢谢def isLeapYear(y): assert y > 1753, False return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)def daysIn(y, m): assert 1 <= m <= 12, False if m == 9 or m == 4 or m == 6 or m == 11: return 30 elif m == 1 or m == 'March' or m == 'May' or m == 'July': return 31 elif m == 8 or m == 10 or m == 12 or m == 3 or m == 5 or m == 7: return 31 elif m == 2 and isLeapYear(y) is True: return 29 elif m == 2 and isLeapYear(y) is False: return 28 else: return Falsedef validDate(y, m, d): try: if daysIn(y, m) and isLeapYear(y): return True except AssertionError: return False if y > 1753 and 1 <= m <= 12 and 1 <= d <= 31: return True elif y == isLeapYear(y) and m == 2 and d == 29: return False else: return Falseif __name__ == "__main__": isLeapYear(2012) daysIn(2012, 10) validDate(1752, 10, 10)
2 回答
Qyouu
TA贡献1786条经验 获得超11个赞
您可以使用标准库 datetime 模块。
from datetime import date
def validDate(y, m, d):
try:
date(y, m, d)
return True
except ValueError:
return False
潇潇雨雨
TA贡献1833条经验 获得超4个赞
问题出在validDate函数中,您不检查日期,而仅检查月份是否有天数(每个月都为 True)。
def validDate(y, m, d):
assert 1 <= d <= daysIn(y, m)
或者如果validDate应该返回一个布尔值,请尝试:
def validDate(y, m, d):
if y <= 1754:
return False
if not (1 <= m <= 12):
return False
if m in (1, 3, 5, 7, 8, 10, 12):
days = 31
elif m == 2:
leap = y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
days = 29 if leap else 28
else:
days = 30
return 1 <= d <= days
添加回答
举报
0/150
提交
取消