Home > Enterprise >  Sorting Array using Sorting Algorithm in PYthon
Sorting Array using Sorting Algorithm in PYthon

Time:12-07

As part of my project, I want to make a database which sorts the Age based on their birthdate.

import datetime

profile = (
    ('Joe', 'Clark', '1989-11-20'),
    ('Charlie', 'Babbitt', '1988-11-20'),
    ('Frank', 'Abagnale', '2002-11-20'),
    ('Bill', 'Clark', '2009-11-20'),
    ('Alan', 'Clark', '1925-11-20'),
    )
age_list = []
for prof in profile:
    date = prof[2]
    datem = datetime.datetime.strptime(date, "%Y-%m-%d")
    tod = datem.day
    mos = datem.month
    yr = datem.year
    today_date = datetime.datetime.now()
    dob = datetime.datetime(yr, mos, tod)
    time_diff = today_date - dob
    Age = time_diff.days // 365
    age_list.append(Age)

def insertionsort(age_list):
    for him in range(1, len(age_list)):
    call = him - 1

    while age_list[call] > age_list[call   1] and call >= 0:
        age_list[call], age_list[call   1] = age_list[call   1], age_list[call]
        call -= 1

print("")
print("\t\t\t\t\t\t\t\t\t\t\t---Insertion Sort---")
print("Sorted Array of Age: ", age_list)

and the output would be:

                            ---Insertion Sort---
 Sorted Array of Age:  [12, 19, 32, 33, 96]

But that's not what I want, I don't want just the Age but also the other elements to be included in the output

So instead of the output earlier, what I want is:

                              ---Insertion Sort---
Sorted Array of Age: [Bill, Clark, 12]
                     [Frank, Abagnale, 19]
                     [Joe, Clark, 32]
                     [Charlie, Babbitt, 33]
                     [Alan, Clark, 96]

Thank you in advanced!

CodePudding user response:

results = sorted(profile, key = lamda x: datetime.datetime.strptime(x[2], "%Y-%m-%d"))

CodePudding user response:

You could do it like this. Note that the strptime function may not be necessary for you but it implicitly validates the format of the date in your input data. Also note that because the dates are in the form of YYYY-MM-DD they can be sorted lexically to give the desired result.

from datetime import datetime
from dateutil.relativedelta import relativedelta

profile = (
    ('Joe', 'Clark', '1989-11-20'),
    ('Charlie', 'Babbitt', '1988-11-20'),
    ('Frank', 'Abagnale', '2002-11-20'),
    ('Bill', 'Clark', '2009-11-20'),
    ('Alan', 'Clark', '1925-11-20')
)

for person in sorted(profile, key=lambda e: e[2], reverse=True):
    age = relativedelta(datetime.today(), datetime.strptime(person[2], '%Y-%m-%d')).years
    print(f'{person[0]}, {person[1]}, {age}')
  • Related