Skip to content

Commit 787aa5d

Browse files
Siddhant231xyzSiddhant Jain
and
Siddhant Jain
authoredJan 13, 2025
doctest all_combinations.py (TheAlgorithms#12506)
* doctest in all_combinations.py * added doctest in all_combinations.py * doctests in all_combinations.py * add doctest all_combinations.py * add --------- Co-authored-by: Siddhant Jain <[email protected]>
1 parent 4c92de5 commit 787aa5d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
 

‎backtracking/all_combinations.py

+34
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
def combination_lists(n: int, k: int) -> list[list[int]]:
1414
"""
15+
Generates all possible combinations of k numbers out of 1 ... n using itertools.
16+
1517
>>> combination_lists(n=4, k=2)
1618
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
1719
"""
@@ -20,6 +22,8 @@ def combination_lists(n: int, k: int) -> list[list[int]]:
2022

2123
def generate_all_combinations(n: int, k: int) -> list[list[int]]:
2224
"""
25+
Generates all possible combinations of k numbers out of 1 ... n using backtracking.
26+
2327
>>> generate_all_combinations(n=4, k=2)
2428
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
2529
>>> generate_all_combinations(n=0, k=0)
@@ -34,6 +38,14 @@ def generate_all_combinations(n: int, k: int) -> list[list[int]]:
3438
ValueError: n must not be negative
3539
>>> generate_all_combinations(n=5, k=4)
3640
[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
41+
>>> generate_all_combinations(n=3, k=3)
42+
[[1, 2, 3]]
43+
>>> generate_all_combinations(n=3, k=1)
44+
[[1], [2], [3]]
45+
>>> generate_all_combinations(n=1, k=0)
46+
[[]]
47+
>>> generate_all_combinations(n=1, k=1)
48+
[[1]]
3749
>>> from itertools import combinations
3850
>>> all(generate_all_combinations(n, k) == combination_lists(n, k)
3951
... for n in range(1, 6) for k in range(1, 6))
@@ -56,6 +68,28 @@ def create_all_state(
5668
current_list: list[int],
5769
total_list: list[list[int]],
5870
) -> None:
71+
"""
72+
Helper function to recursively build all combinations.
73+
74+
>>> create_all_state(1, 4, 2, [], result := [])
75+
>>> result
76+
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
77+
>>> create_all_state(1, 3, 3, [], result := [])
78+
>>> result
79+
[[1, 2, 3]]
80+
>>> create_all_state(2, 2, 1, [1], result := [])
81+
>>> result
82+
[[1, 2]]
83+
>>> create_all_state(1, 0, 0, [], result := [])
84+
>>> result
85+
[[]]
86+
>>> create_all_state(1, 4, 0, [1, 2], result := [])
87+
>>> result
88+
[[1, 2]]
89+
>>> create_all_state(5, 4, 2, [1, 2], result := [])
90+
>>> result
91+
[]
92+
"""
5993
if level == 0:
6094
total_list.append(current_list[:])
6195
return

0 commit comments

Comments
 (0)
Please sign in to comment.