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)