题目地址:日期问题
此题比较重视细节,尽管你做出来也可能并不是100%,找了一个多小时bug的我亲身经历。
具体思路:将所有可能的结果保存到列表中,最后一个个进行判断。
1.先处理相应数据:
date = input()
AA = date[:2]
BB = date[3:5]
CC = date[6:8]
2.题目中明确写到“有采用年/月/日的,有采用月/日/年的,还有采用日/月/年的”,所以我们只考虑这三种情况:
# 年月日
if int(AA) >= 60:
dates.append('19' + AA + BB + CC)
else:
dates.append('20' + AA + BB + CC)
# 月日年与日月年
if int(CC) >= 60:
dates.append('19' + CC + AA + BB)
dates.append('19' + CC + BB + AA)
else:
dates.append('20' + CC + AA + BB)
dates.append('20' + CC + BB + AA)
3.利用for循环进行判断:
for datee in dates:
if datee in ans: # 确保不会存在相同的日期
continue
year = int(datee[:4])
month = int(datee[4:6])
day = int(datee[6:8])
if month > 12 or day > 31 or month < 1 or day < 1: # 后面相应的< 1一定要添加,否则会有一例失败
continue
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0): # 是闰年
if day <= rmonthes[month]: # 判断日期
ans.append(datee)
else:
if day <= monthes[month]: # 判断日期
ans.append(datee)
完整代码:
date = input()
AA = date[:2]
BB = date[3:5]
CC = date[6:8]
monthes=[0,31,28,31,30,31,30,31,31,30,31,30,31] # 非闰年专用
rmonthes=[0,31,29,31,30,31,30,31,31,30,31,30,31] # 闰年专用
# 年月日 月日年 日月年
dates = []
ans = []
# 年月日
if int(AA) >= 60:
dates.append('19' + AA + BB + CC)
else:
dates.append('20' + AA + BB + CC)
# 月日年与日月年
if int(CC) >= 60:
dates.append('19' + CC + AA + BB)
dates.append('19' + CC + BB + AA)
else:
dates.append('20' + CC + AA + BB)
dates.append('20' + CC + BB + AA)
for datee in dates:
if datee in ans: # 确保不会存在相同的日期
continue
year = int(datee[:4])
month = int(datee[4:6])
day = int(datee[6:8])
if month > 12 or day > 31 or month < 1 or day < 1: # 后面相应的< 1一定要添加,否则会有一例失败
continue
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0): # 是闰年
if day <= rmonthes[month]: # 判断日期
ans.append(datee)
else:
if day <= monthes[month]: # 判断日期
ans.append(datee)
ans.sort() # 字符串也会进行排序,不用再转int
for datee in ans:
print(f'{datee[:4]}-{datee[4:6]}-{datee[6:8]}')