Skip to content

Commit b3b9b57

Browse files
committed
fix: now calculates the accurate ages by handling the mid-year birthdays correctly
1 parent 03bed6a commit b3b9b57

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

prep_exercises/exercise6.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,24 @@
55
@dataclass(frozen=True)
66
class Person:
77
name: str
8-
age: int
8+
birth_date: date
99
children: List["Person"]
1010

11-
fatma = Person(name="Fatma", birth_year=2011, children=[])
12-
aisha = Person(name="Aisha", birth_year=2015, children=[])
11+
fatma = Person(name="Fatma", birth_date=date(2011, 5, 10), children=[])
12+
aisha = Person(name="Aisha", birth_date=date(2015, 8, 22), children=[])
1313

14-
imran = Person(name="Imran", birth_year=2000, children=[fatma, aisha])
14+
imran = Person(name="Imran", birth_date=date(2000, 3, 15), children=[fatma, aisha])
1515

16-
def current_age(birth_year:int) -> int:
16+
def current_age(birth_date: date) -> int:
1717
today = date.today()
18-
return today.year - birth_year
18+
age = today.year - birth_date.year
19+
if (today.month, today.day) < (birth_date.month, birth_date.day):
20+
age -= 1
21+
return age
1922

2023
def print_family_tree(person: Person) -> None:
21-
print(f"{person.name} ({current_age(person.birth_year)})")
24+
print(f"{person.name} ({current_age(person.birth_date)})")
2225
for child in person.children:
23-
print(f"- {child.name} ({current_age(child.birth_year)})")
26+
print(f"- {child.name} ({current_age(child.birth_date)})")
2427

2528
print_family_tree(imran)

0 commit comments

Comments
 (0)