问题描述
小明正在整理一批历史文献。这些历史文献中出现了很多日期。小明知道这些日
期都在 1960 年 1 月 1 日至 2059 年 12 月 31 日。令小明头疼的是,这些日期采
用的格式非常不统一,有采用年/月/日的,有采用月/日/年的,还有采用日/月/年
的。更加麻烦的是,年份也都省略了前两位,使得文献上的一个日期,存在很多
可能的日期与其对应。
比如 02/03/04,可能是 2002 年 03 月 04 日、2004 年 02 月 03 日或 2004 年 03
月 02 日。
给出一个文献上的日期,你能帮助小明判断有哪些可能的日期对其对应吗?
输入
一个日期,格式是"AA/BB/CC"。 (0 <= A, B, C <= 9)
输出
输出若干个不相同的日期,每个日期一行,格式是"yyyy-MM-dd"。多个日期按
从早到晚排列。
样例输入
02/03/04
样例输出
2002-03-04
2004-02-03
2004-03-02
思路分析及代码实现
方法一 巧用time库
import time
str = input()
AA = str[0:2]
BB = str[3:5]
CC = str[6:8]
# 三种形式
date1 = AA+'-'+BB+'-'+CC
date2 = CC+'-'+AA+'-'+BB
date3 = CC+'-'+BB+'-'+AA
date1 = [date1,date2,date3]
# 判断日期是否合法
def isVaildDate( date):
try:
if ":" in date:
time.strptime(date, "%Y-%m-%d %H:%M:%S")
else:
time.strptime(date, "%Y-%m-%d")
return True
except:
return False
#对date1进行遍历,对年份进行补齐
for i in range(len(date1)):
if int(date1[i][0:2])>=60:
date1[i] = '19'+date1[i]
else:
date1[i] = '20' + date1[i]
# 对date1进行遍,保留合法数据于date[]中
date = []
for temp in date1:
if isVaildDate(date=temp):
date.append(temp)
# 对日期用冒泡排序进行排序
for i in range(len(date)):
for j in range(len(date)-i-1):
e_time1 = time.strptime(date[j],'%Y-%m-%d') #将日期转换成秒
e_time2 = time.strptime(date[j+1],'%Y-%m-%d')#同上
if e_time1>e_time2:
temp = date[j]
date[j] = date[j+1]
date[j+1] = temp
for temp in date:
print(temp)
方法二 常规做法
判断年份(平闰年) 判断月份 判断日期
while True:
try:
a = list(map(int, input().split("/")))
res = []
def isRN(year):
if year % 4 == 0 and year % 100 != 0:
return True
elif year % 400 == 0:
return True
else:
return False
def f(x, y, z): # 默认年月日
if x >= 0 and x <= 59:
x += 2000
elif x >= 60 and x <= 99:
x += 1900
if y <= 0 or y > 12:
return False
if z <= 0 or z > 31:
return False
if isRN(x) and y == 2 and z > 29:
return False
if isRN(x) == False and y == 2 and z > 28:
return False
if y == 4 and z > 30:
return False
if y == 6 and z > 30:
return False
if y == 9 and z > 30:
return False
if y == 11 and z > 30:
return False
else:
if y < 10:
y = str(0) + str(y)
if z < 10:
z = str(0) + str(z)
res.append(str(x) + "-" + str(y) + '-' + str(z))
return
f(a[0], a[1], a[2])
f(a[2], a[0], a[1])
f(a[2], a[1], a[0])
for i in sorted(list(set(res))):
print(i)
except:
break