Skip to content

Commit 9d20fbf

Browse files
authored
Add recursive example for finding a key in nested boxes (Python) (egonSchiele#290)
1 parent 775022b commit 9d20fbf

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Item have 2 types: key or box
2+
class Item:
3+
def __init__(self, is_key=False):
4+
self.is_key = is_key
5+
6+
# If not a key, it's a box that can hold items
7+
self.items_in_box = []
8+
9+
def is_a_box(self):
10+
return not self.is_key
11+
12+
def is_a_key(self):
13+
return self.is_key
14+
15+
16+
def look_for_key(box: Item):
17+
for item in box.items_in_box:
18+
if item.is_a_box():
19+
# recursive case
20+
look_for_key(item)
21+
elif item.is_a_key():
22+
# base case
23+
print("found the key!")
24+
25+
26+
"""
27+
main_box
28+
├── box_A
29+
│ ├── box_B
30+
│ └── box_C
31+
└── box_D
32+
└── box_E
33+
└── key
34+
"""
35+
main_box = Item()
36+
37+
box_A = Item()
38+
box_B = Item()
39+
box_C = Item()
40+
box_A.items_in_box = [box_B, box_C]
41+
42+
box_D = Item()
43+
box_E = Item()
44+
key = Item(is_key = True)
45+
box_E.items_in_box = [key]
46+
box_D.items_in_box = [box_E]
47+
48+
main_box.items_in_box = [box_A, box_D]
49+
50+
look_for_key(main_box)

0 commit comments

Comments
 (0)