0

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!

Hydroxy21
  • 17
  • 6

3 Answers3

1

As you want to keep your own insertion sort implementation, I would suggest putting the date of birth as the first tuple member: that way you can just compare tuples in your sorting implementation. The date of birth is in fact a better value to sort by (but reversed) than the age, as the date has more precision (day) compared to the age (year).

Secondly, your algorithm to calculate the age is error prone, as not all years have 365 days. Use the code as provided in this question:

import datetime


def calculate_age(born):
    today = datetime.date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))


def insertionsort(lst):
    for i, value in enumerate(lst):
        for j in range(i - 1, -1, -1):
            if lst[j] > value:  # this will give a sort in descending order
                break
            lst[j], lst[j + 1] = lst[j + 1], lst[j]

# Your example data as a list
profiles = [
    ('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'),
]

# Put date of birth first, and append age
profiles = [(dob, first, last, calculate_age(datetime.datetime.strptime(dob, "%Y-%m-%d"))) 
    for first, last, dob in profiles]

insertionsort(profiles)

print(profiles)
trincot
  • 317,000
  • 35
  • 244
  • 286
0
results = sorted(profile, key = lamda x: datetime.datetime.strptime(x[2], "%Y-%m-%d"))
Larry the Llama
  • 958
  • 3
  • 13
0

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}')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Thanks, that's the output that I want, but it is not the process of my prof wants. He wants me to use the sorting algorithm in doing that. – Hydroxy21 Dec 07 '21 at 12:33
  • I suggest you ask your "professor" why he wants you to use an inefficient sorting implementation. – DarkKnight Dec 07 '21 at 12:53