Skip to content

Commit b3a5cae

Browse files
committed
print recursive
1 parent 40a13c5 commit b3a5cae

File tree

1 file changed

+16
-12
lines changed

1 file changed

+16
-12
lines changed

prep-exercices/generics.py

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
1-
2-
#EXERCISE 1: Fix the above code so that it works. You must not change the print on line 17
3-
# we do want to print the children’s ages. (Feel free to invent the ages of Imran’s children)
4-
5-
# SOLUTION:
6-
71
from dataclasses import dataclass
82
from typing import List
93

104
@dataclass(frozen=True)
115
class Person:
126
name: str
137
age: int = 0
14-
children: List["Person"]
8+
children: List["Person"] = None
9+
10+
def __post_init__(self):
11+
# Ensure children is always a list
12+
object.__setattr__(self, "children", self.children or [])
1513

14+
# Example family
1615
fatma = Person(name="Fatma", age=18, children=[])
1716
aisha = Person(name="Aisha", age=24, children=[])
17+
zara = Person(name="Zara", age=2, children=[]) # Fatma's child
18+
fatma = Person(name="Fatma", age=18, children=[zara]) # Fatma now has a child
1819

19-
imran = Person(name="Imran", age=45, children=[fatma aisha])
20+
imran = Person(name="Imran", age=45, children=[fatma, aisha])
2021

21-
def print_family_tree(person: Person) -> None:
22-
print(person.name)
22+
def print_family_tree(person: Person, level: int = 0) -> None:
23+
# Prints a person's name and age, then recursively prints all descendants
24+
indent = " " * level # 2 spaces per generation
25+
print(f"{indent}- {person.name} ({person.age})")
2326
for child in person.children:
24-
print(f"- {child.name} ({child.age})")
27+
print_family_tree(child, level + 1)
2528

26-
print_family_tree(imran)
29+
# Print the full family tree
30+
print_family_tree(imran)

0 commit comments

Comments
 (0)