samedi 25 septembre 2021

How would you shorten this long winded if/elif function?

This code works as intended but is not very elegant. I am looking for different perspectives or better methods of getting the same result. Also if you have any recommendations for naming conventions when it comes to variables for code readability, feedback is welcome.

def get_oldest(date1, date2):
    """Given 2 date strings in "MM/DD/YYYY" format, return oldest one."""
    date_one = date1.split("/")
    date_two = date2.split("/")
    if date_one[2] < date_two[2]:
        return date1
    elif date_one[2] > date_two[2]:
        return date2
    elif date_one[2] == date_two[2]:
        if date_one[0] < date_two[0]:
            return date1
        elif date_one[0] > date_two[0]:
            return date2
        elif date_one[0] == date_two[0]:
            if date_one[1] < date_two[1]:
                return date1
            elif date_one[1] > date_two[1]:
                return date2
            elif date_one[1] == date_two[1]:
                return date1


get_oldest("06/21/1958", "06/24/1958")

Aucun commentaire:

Enregistrer un commentaire