Created
February 5, 2012 09:40
-
-
Save zrbecker/1744440 to your computer and use it in GitHub Desktop.
Expiration Date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def Permute(list): | |
| if len(list) == 0: | |
| return [] | |
| elif len(list) == 1: | |
| return [list] | |
| else: | |
| perms = [] | |
| for n in list: | |
| rest = list[:] | |
| rest.remove(n) | |
| rest_perms = Permute(rest) | |
| for perm in rest_perms: | |
| perms.append([n] + perm) | |
| return perms | |
| def IsLeapYear(year): | |
| return (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0) | |
| def IsValidDate(year, month, day): | |
| if year >= 2000 and year <= 2999: | |
| if month >= 1 and month <= 12: | |
| if month in [4, 6, 9, 11]: | |
| return (day >= 1 and day <= 30) | |
| elif month in [1, 3, 5, 7, 8, 10, 12]: | |
| return (day >= 1 and day <= 31) | |
| elif IsLeapYear(year): | |
| return (day >= 1 and day <= 29) | |
| else: | |
| return (day >= 1 and day <= 28) | |
| return False | |
| def FormatDate(year, month, day): | |
| if year < 2000: | |
| year += 2000 | |
| return (year, month, day) | |
| def ParseEarliestDate(input_date): | |
| date_array = input_date.split("/") | |
| if len(date_array) != 3: | |
| return input_date + " is illegal" | |
| try: | |
| date_array[0] = int(date_array[0]) | |
| date_array[1] = int(date_array[1]) | |
| date_array[2] = int(date_array[2]) | |
| except: | |
| return input_date + " is illegal" | |
| date_perms = [FormatDate(*date) for date in Permute(date_array)] | |
| valid_dates = [date for date in date_perms if IsValidDate(*date)] | |
| if len(valid_dates) == 0: | |
| return input_date + " is illegal" | |
| year, month, day = sorted(valid_dates)[0] | |
| return "%.4d-%.2d-%.2d" % (year, month, day) | |
| if __name__ == '__main__': | |
| import sys | |
| if len(sys.argv) != 2: | |
| print "Usage: %s date_string" % (sys.argv[0]) | |
| else: | |
| print ParseEarliestDate(sys.argv[1]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment