问题描述
本题为填空题,只需要算出结果后,在代码中使用输出语句将所填结果输出即可。
小明特别喜欢顺子。顺子指的就是连续的三个数字:123、456 等。顺子日期指的就是在日期的 yyyymmdd 表示法中,存在任意连续的三位数是一个顺子的日期。例如 20220123 就是一个顺子日期,因为它出现了一个顺子:123; 而 20221023 则不是一个顺子日期,它一个顺子也没有。小明想知道在整个 2022 年份中,一共有多少个顺子日期?
运行限制
- 最大运行时间:1s
- 最大运行内存: 512M
思路
枚举法
答案
14
利用日期函数做时间变化
import datetime
shunzi = ["012","123","234","345","456","567","678","789"]
res = 0
d = datetime.datetime(2022,1,1)
for i in range(365):
if d.month < 10:
month = "0" + str(d.month)
else:
month = str(d.month)
if d.day < 10:
day = "0" + str(d.day)
else:
day = str(d.day)
end = month + day
if end[:3] in shunzi or end[1:4] in shunzi:
res += 1
d += datetime.timedelta(days = 1)
print(res)
或者
import datetime
start = datetime.datetime(2022,1,1)
end = datetime.datetime(2022,12,31)
shunzi = ["012","123","234","345","456","678","789"]
cnt = 0
while start <= end:
y4 = start.year%10
m2 = start.month%10
m1 = start.month//10
d2 = start.day%10
d1 = start.day//10
s2 = str(m2)+str(m1)+str(d2)
s3 = str(m1)+str(d2)+str(d1)
if s2 in shunzi or s3 in shunzi:
cnt += 1
start += datetime.timedelta(days=1)
print(cnt)