算法测试系列:Palindrome Dates

Palindrome Dates

A palindrome date is the kind of date which reads the same backward or forward, in the MM/DD/YYYY format. There are 2 types of palindrome dates: seven-digit palindrome date and eight-
digit palindrome date. For example, October 2, 2001 is the first eight-digit palindrome date (10022001) and September 2, 2090 is the last eight-digit palindrome date (09022090) in the 21st
Century; Likewise, January 10, 2011 is the first seven-digit palindrome date (1102011) and September 30, 2039 (9302039) is the last seven-digit palindrome date in the 21st Century. Yeah, I
know, it’s fun!

Here comes the question. Given a year in YYYY format (an integer), can you come up with an algo that outputs the total number of palindrome dates (both seven-digit and eight-digit types) in
its century? For example, if you are given the number 2016, your function should return 38 – There are 38 palindrome dates in the 21st Century.

Please ignore all the years prior to 1000 and later than 9999 (not our concern!). You will only be given years that are in the four-digit format (1000-9999).

from calendar import monthrange
def get_palindrome_date(y):
    """
    This function return palindrome date in a century 
    :param y: 
    :return: 
    """
    
    century_start = (y // 100) * 100 + 1
    century_end = century_start + 99
    count = 0
    for year in range(century_start, century_end):
        for month in range(1, 13):
            number_of_days = monthrange(year, month)[1]
            flag = False
            if len(str(month)) == 1:
                month_string = '0' + str(month)
                flag = True
            else:
                month_string = str(month)
            for day in range(1, number_of_days + 1):
                if len(str(day)) == 1:
                    date_string = month_string + '0' + str(day) + str(year)
                else:
                    date_string = month_string + str(day) + str(year)

                if list(reversed(date_string)) == list(date_string):
                    count += 1
                elif flag and list(reversed(date_string[0:len(date_string) - 1])) == list(
                        date_string[0:len(date_string) - 1]):
                    count += 1

                elif flag and list(reversed(date_string[1:len(date_string)])) == list(date_string[1:len(date_string)]):
                    count += 1

    return count

get_palindrome_date(2020)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值