小学生蓝桥杯Python闯关 | 特殊时间

学习Python从娃娃抓起!记录下蓝桥杯Python学习和备考过程中的题目,记录每一个瞬间。

附上汇总贴:小学生蓝桥杯Python闯关 | 汇总_COCOgsta的博客-CSDN博客


【题目描述】

2022年2月22日22:20是一个很有意义的时间,年份为2022,由3个2和1个0组成,如果将月和日写成4位,为0222,也由3个2和1个0组成,如果将时间中的时和分写成4位,还由3个2和1个0组成。小蓝对这样的时间很感兴趣,他还找到了其他类似的例子,如111年10月11日01:11、2202年2月22日22:02等。请问,总共有多少个时间是这种年份写成4位、月日写成4位、时间写成4位后均由3个一种数字和1个另一种数字组成的。注意1111年11月11日11:11不算,因为它里面没有两种数字。

【代码详解】

def check(n):                  #检查数字是否合法,n是排序后的
    if n[0] == n[3]: return False
    if n[1] != n[2]: return False
    if n[0] == n[1] or n[2]==n[3]: return True
    return False
year=[]
for y in range(1,10000):       #0001年~9999年
    s="%04d" %(y)
    s1=sorted(s)
    if check(s1):  year.append(s1)
day=[]
for m in range(1,13):          #12个月
    for d in range(1,31):      #30日、31日都不符合要求,不用管。同理2月29日、2月30日也不用管
        s="%02d%02d" %(m,d)
        s1=sorted(s)
        if check(s1):
            day.append(s1)
hour=[]
for h in range(0,24):
    for m in range(0,60):
        s="%02d%02d" %(h,m)
        s1=sorted(s)
        if check(s1):
            hour.append(s1)
cnt = 0
for i in year:                #遍历年
    for j in day:             #遍历月日
        for k in hour:        #遍历时分
            if i==j and i==k:  cnt+=1
print(cnt)                    #输出212
复制代码

【运行结果】

212

猜你喜欢

转载自blog.csdn.net/guolianggsta/article/details/129803206