I need some help to understand how this works. The task is to make a function (printAgeDiff) with (table) as a parameter. (table) is a two-dimensional list with names and date of birth on four people:
table=[['Justin','Bieber',1994,3,1],
['Donald','Duck',1934,8,1],
['George','Clooney',1961,5,6],
['Eddie','Murphy',1961,4,3]]
Compare the age of the people and print the following based on the age-difference:
If person n and person n 1 has the same age:
<firstname> <lastname> is at the same age as <firstname 1> <lastname 1>
If person n is older then person n 1:
<firstname> <lastname> is older then <firstname 1> <lastname 1>
If person n is younger then person n 1:
<firstname> <lastname> is younger then <firstname 1> <lastname 1>
Eksample on the print: printAgeDiff(table) Justin Bieber is younger than Donald Duck Donald Duck is older than George Clooney George Clooney is at the same age as Eddie Murphy
I have created the first set of the program whitch is programming todays date and also a function that print the age based on the date of birth, but I really struggle with slicing the table and sending it through my findAge function
I really aprreciate some help
CodePudding user response:
Convert the year, month, date columns into datetime objects, which are easier to compare. Then use itertools.combinations to retrieve the possible combinations. Finally, check your conditions.
from datetime import datetime
import itertools
table = [['Justin','Bieber',1994,3,1],
['Donald','Duck',1934,8,1],
['George','Clooney',1961,5,6],
['Eddie','Murphy',1961,4,3]]
def printAgeDifference(table):
datetimeTable = [[" ".join(person[:2]), datetime(*person[-3:])] for person in table]
for person_a, person_b in itertools.combinations(datetimeTable, 2):
if person_a == person_b:
print(f"{person_a[0]} is at the same age as {person_b[0]}")
continue
if person_a < person_b:
print(f"{person_a[0]} is older then {person_b[0]}")
continue
print(f"{person_a[0]} is younger then {person_b[0]}")
printAgeDifference(table)
Output:
Justin Bieber is younger then Donald Duck
Justin Bieber is younger then George Clooney
Justin Bieber is younger then Eddie Murphy
Donald Duck is older then George Clooney
Donald Duck is older then Eddie Murphy
George Clooney is younger then Eddie Murphy