Skip to content

Instantly share code, notes, and snippets.

@grubberr
Last active May 21, 2018 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grubberr/e49d716f0c11121201cf8baa1d80de11 to your computer and use it in GitHub Desktop.
Save grubberr/e49d716f0c11121201cf8baa1d80de11 to your computer and use it in GitHub Desktop.
find earliest possible legal date in A/B/C format
#!/usr/bin/python3
import sys
import itertools
from datetime import datetime
def main(s):
" find earliest possible legal date or raise ValueError "
def check_str(s):
if not s.isdigit():
raise ValueError('invalid value %s' % s)
if len(s) not in (1, 2, 4):
raise ValueError('invalid value %s' % s)
return s
def check_number(n):
if not ((0 <= n <= 99) or (2000 <= n <= 2999)):
raise ValueError('invalid value %d' % n)
return n
res = [check_number(int(check_str(i))) for i in s.split('/')]
try:
(a, b, c) = res
except ValueError:
raise ValueError('invalid date, has to be 3 items')
valid_dates = []
def normalize_year(n):
if n <= 99:
n += 2000
return n
for (year, month, day) in itertools.permutations((a, b, c)):
year = normalize_year(year)
try:
valid_dates.append(datetime(year, month, day))
except ValueError:
pass
if not valid_dates:
raise ValueError('invalid date')
return min(valid_dates).strftime('%Y-%m-%d')
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: {} FILE'.format(__file__))
sys.exit(1)
with open(sys.argv[1]) as fp:
s = fp.read().strip()
try:
print(main(s))
except ValueError:
print(repr(s), 'is illegal')
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment