Skip to content

Commit 4496f7c

Browse files
authored
Create sublists.py
Add generate_sublists.py with recursive and backtracking implementations - Implement generate_sublists_recursive to generate all sublists using recursion - Implement generate_sublists_backtrack to generate all sublists using backtracking - Include docstrings with examples for both functions - Add a main execution block for testing using doctest
1 parent 0139143 commit 4496f7c

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

data_structures/arrays/sublists.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
def generate_sublists_recursive(lst: list[int]) -> list[list[int]]:
2+
"""
3+
Generate all sublists of the given list, including the empty sublist using a recursive approach.
4+
5+
>>> generate_sublists_recursive([1, 2, 3])
6+
[[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
7+
"""
8+
def helper(start: int) -> None:
9+
if start == len(lst):
10+
return
11+
for end in range(start + 1, len(lst) + 1):
12+
result.append(lst[start:end])
13+
helper(start + 1)
14+
15+
result: list[list[int]] = [[]]
16+
helper(0)
17+
return result
18+
19+
20+
def generate_sublists_backtrack(lst: list[int]) -> list[list[int]]:
21+
"""
22+
Generate all sublists of the given list, including the empty sublist using a backtracking approach.
23+
24+
>>> generate_sublists_backtrack([1, 2, 3])
25+
[[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
26+
"""
27+
def backtrack(start: int, current: list[int]) -> None:
28+
result.append(current[:])
29+
for end in range(start, len(lst)):
30+
current.append(lst[end])
31+
backtrack(end + 1, current)
32+
current.pop()
33+
34+
result: list[list[int]] = []
35+
backtrack(0, [])
36+
return result
37+
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
42+
print(generate_sublists_recursive([1, 2, 3]))
43+
print(generate_sublists_backtrack([1, 2, 3]))
44+
doctest.testmod()

0 commit comments

Comments
 (0)