|
1 | 1 | from dataclasses import dataclass |
2 | 2 | from typing import List |
| 3 | +from datetime import date |
3 | 4 |
|
4 | 5 | @dataclass(frozen=True) |
5 | 6 | class Person: |
6 | 7 | name: str |
7 | | - age: int |
| 8 | + date_of_birth: date |
8 | 9 | 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 |
9 | 17 |
|
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) |
12 | 25 |
|
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=[]) |
15 | 28 |
|
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]) |
17 | 33 |
|
18 | 34 | def print_family_tree(person: Person) -> None: |
19 | | - print(f"{person.name} ({person.age})") |
| 35 | + print(f"{person.name} ({person.age()})") |
20 | 36 | for child in person.children: |
21 | | - print(f" - {child.name} ({child.age})") |
| 37 | + print(f" - {child.name} ({child.age()})") |
22 | 38 | for grandchild in child.children: |
23 | | - print(f" - {grandchild.name} ({grandchild.age})") |
| 39 | + print(f" - {grandchild.name} ({grandchild.age()})") |
24 | 40 |
|
25 | 41 | def count_family_members(person: Person) -> int: |
26 | 42 | count = 1 |
|
0 commit comments