Sort an Array of dates in ascending order using Custom Comparator | Python3 implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Comparator to sort the array of dates ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver Code
from functools import cmp_to_key NEW_LINE def myCompare ( date1 , date2 ) : NEW_LINE INDENT day1 = date1 [ 0 : 2 ] NEW_LINE month1 = date1 [ 3 : 3 + 2 ] NEW_LINE year1 = date1 [ 6 : 6 + 4 ] NEW_LINE day2 = date2 [ 0 : 2 ] NEW_LINE month2 = date2 [ 3 : 3 + 2 ] NEW_LINE year2 = date2 [ 6 : 6 + 4 ] NEW_LINE if ( year1 < year2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( year1 > year2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( month1 < month2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( month1 > month2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( day1 < day2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( day1 > day2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT def printDatesAscending ( arr ) : NEW_LINE INDENT arr = sorted ( arr , key = cmp_to_key ( lambda a , b : myCompare ( a , b ) ) ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT DEDENT arr = [ ] NEW_LINE arr . append ( "25-08-1996" ) NEW_LINE arr . append ( "03-08-1970" ) NEW_LINE arr . append ( "09-04-1994" ) NEW_LINE arr . append ( "29-08-1996" ) NEW_LINE arr . append ( "14-02-1972" ) NEW_LINE printDatesAscending ( arr ) NEW_LINE