Skip to content

Commit 380df70

Browse files
committed
Replace hard-coded age with dynamic calculation from date_of_birth
1 parent 099d936 commit 380df70

1 file changed

Lines changed: 25 additions & 9 deletions

File tree

prep-exercises/generics.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,42 @@
11
from dataclasses import dataclass
22
from typing import List
3+
from datetime import date
34

45
@dataclass(frozen=True)
56
class Person:
67
name: str
7-
age: int
8+
date_of_birth: date
89
children: List["Person"]
10+
11+
def age(self) -> int:
12+
current_date = date.today()
13+
age = current_date.year - self.date_of_birth.year - (
14+
(current_date.month, current_date.day) < (self.date_of_birth.month, self.date_of_birth.day)
15+
)
16+
return age
917

10-
sara = Person(name="Sara", age=5, children=[])
11-
ahmed = Person(name="Ahmed", age=8, children=[])
18+
# Calculate dates of birth based on current age
19+
def years_ago(years: int) -> date:
20+
today = date.today()
21+
try:
22+
return date(today.year - years, today.month, today.day)
23+
except ValueError: # Handle leap year edge case (Feb 29)
24+
return date(today.year - years, today.month, today.day - 1)
1225

13-
ali = Person(name="Ali", age=28, children=[sara])
14-
aya = Person(name="Aya", age=32, children=[ahmed])
26+
sara = Person(name="Sara", date_of_birth=years_ago(5), children=[])
27+
ahmed = Person(name="Ahmed", date_of_birth=years_ago(8), children=[])
1528

16-
imran = Person(name="Imran", age=55, children=[ali, aya])
29+
ali = Person(name="Ali", date_of_birth=years_ago(28), children=[sara])
30+
aya = Person(name="Aya", date_of_birth=years_ago(32), children=[ahmed])
31+
32+
imran = Person(name="Imran", date_of_birth=years_ago(55), children=[ali, aya])
1733

1834
def print_family_tree(person: Person) -> None:
19-
print(f"{person.name} ({person.age})")
35+
print(f"{person.name} ({person.age()})")
2036
for child in person.children:
21-
print(f" - {child.name} ({child.age})")
37+
print(f" - {child.name} ({child.age()})")
2238
for grandchild in child.children:
23-
print(f" - {grandchild.name} ({grandchild.age})")
39+
print(f" - {grandchild.name} ({grandchild.age()})")
2440

2541
def count_family_members(person: Person) -> int:
2642
count = 1

0 commit comments

Comments
 (0)