How to resolve the algorithm Palindrome dates step by step in the Python programming language
How to resolve the algorithm Palindrome dates step by step in the Python programming language
Table of Contents
Problem Statement
Today (2020-02-02, at the time of this writing) happens to be a palindrome, without the hyphens, not only for those countries which express their dates in the yyyy-mm-dd format but, unusually, also for countries which use the dd-mm-yyyy format.
Write a program which calculates and shows the next 15 palindromic dates for those countries which express their dates in the yyyy-mm-dd format.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Palindrome dates step by step in the Python programming language
This code defines a function that generates palindromic dates for a given year. A palindromic date is a date that reads the same forwards and backwards, such as "2020-02-02".
The function, called palinDay
, takes a year as input and returns a list of palindromic dates for that year. The function first converts the year to a string, then reverses the string, and then joins the original string with the reversed string to create a potential palindromic date. The function then tries to parse the potential palindromic date as a date object using the datetime.strptime
function. If the date object can be parsed successfully, the function returns a list containing the palindromic date. Otherwise, the function returns an empty list.
The code also includes a main
function that tests the palinDay
function by generating a list of palindromic dates for the years 2021 to 9999. The main
function then prints the count of palindromic dates for those years, as well as the first and last 15 palindromic dates.
The output of the main
function is as follows:
Count of palindromic dates [2021..9999]:
101
First 15:
2021-02-02
2021-11-12
2022-01-01
2022-10-10
2023-01-03
2023-02-02
2023-11-13
2024-01-04
2024-10-10
2025-01-05
2025-02-02
2025-12-12
2026-01-06
2026-10-10
2027-01-07
Last 15:
9978-12-12
9979-01-09
9979-02-09
9979-11-19
9980-01-10
9980-02-02
9980-10-10
9981-01-11
9981-02-02
9981-11-11
9982-01-12
9982-02-02
9982-11-12
9983-01-13
9983-02-02
Source code in the python programming language
'''Palindrome dates'''
from datetime import datetime
from itertools import chain
# palinDay :: Int -> [ISO Date]
def palinDay(y):
'''A possibly empty list containing the palindromic
date for the given year, if such a date exists.
'''
s = str(y)
r = s[::-1]
iso = '-'.join([s, r[0:2], r[2:]])
try:
datetime.strptime(iso, '%Y-%m-%d')
return [iso]
except ValueError:
return []
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Count and samples of palindromic dates [2021..9999]
'''
palinDates = list(chain.from_iterable(
map(palinDay, range(2021, 10000))
))
for x in [
'Count of palindromic dates [2021..9999]:',
len(palinDates),
'\nFirst 15:',
'\n'.join(palinDates[0:15]),
'\nLast 15:',
'\n'.join(palinDates[-15:])
]:
print(x)
# MAIN ---
if __name__ == '__main__':
main()
'''Palindrome dates'''
from functools import reduce
from itertools import chain
from datetime import date
# palinDay :: Integer -> [ISO Date]
def palinDay(y):
'''A possibly empty list containing the palindromic
date for the given year, if such a date exists.
'''
[m, d] = [undigits(pair) for pair in chunksOf(2)(
reversedDecimalDigits(y)
)]
return [] if (
1 > m or m > 12 or 31 < d
) else validISODate((y, m, d))
# --------------------------TEST---------------------------
# main :: IO ()
def main():
'''Count and samples of palindromic dates [2021..9999]
'''
palinDates = list(chain.from_iterable(
map(palinDay, range(2021, 10000))
))
for x in [
'Count of palindromic dates [2021..9999]:',
len(palinDates),
'\nFirst 15:',
'\n'.join(palinDates[0:15]),
'\nLast 15:',
'\n'.join(palinDates[-15:])
]:
print(x)
# -------------------------GENERIC-------------------------
# Just :: a -> Maybe a
def Just(x):
'''Constructor for an inhabited Maybe (option type) value.
Wrapper containing the result of a computation.
'''
return {'type': 'Maybe', 'Nothing': False, 'Just': x}
# Nothing :: Maybe a
def Nothing():
'''Constructor for an empty Maybe (option type) value.
Empty wrapper returned where a computation is not possible.
'''
return {'type': 'Maybe', 'Nothing': True}
# chunksOf :: Int -> [a] -> [[a]]
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divible, the final list will be shorter than n.
'''
return lambda xs: reduce(
lambda a, i: a + [xs[i:n + i]],
range(0, len(xs), n), []
) if 0 < n else []
# reversedDecimalDigits :: Int -> [Int]
def reversedDecimalDigits(n):
'''A list of the decimal digits of n,
in reversed sequence.
'''
return unfoldr(
lambda x: Nothing() if (
0 == x
) else Just(divmod(x, 10))
)(n)
# unDigits :: [Int] -> Int
def undigits(xs):
'''An integer derived from a list of decimal digits
'''
return reduce(lambda a, x: a * 10 + x, xs, 0)
# unfoldr(lambda x: Just((x, x - 1)) if 0 != x else Nothing())(10)
# -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
# unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
def unfoldr(f):
'''Dual to reduce or foldr.
Where catamorphism reduces a list to a summary value,
the anamorphic unfoldr builds a list from a seed value.
As long as f returns Just(a, b), a is prepended to the list,
and the residual b is used as the argument for the next
application of f.
When f returns Nothing, the completed list is returned.
'''
def go(v):
xr = v, v
xs = []
while True:
mb = f(xr[0])
if mb.get('Nothing'):
return xs
else:
xr = mb.get('Just')
xs.append(xr[1])
return xs
return go
# validISODate :: (Int, Int, Int) -> [Date]
def validISODate(ymd):
'''A possibly empty list containing the
ISO8601 string for a date, if that date exists.
'''
try:
return [date(*ymd).isoformat()]
except ValueError:
return []
# MAIN ---
if __name__ == '__main__':
main()
You may also check:How to resolve the algorithm Keyboard input/Keypress check step by step in the RPL programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Null object step by step in the Maxima programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the Nim programming language
You may also check:How to resolve the algorithm Loops/For step by step in the PicoLisp programming language