Skip to content

Commit d9a11a9

Browse files
moaldeencclauss
andcommitted
Bug fix combinations (TheAlgorithms#11158)
* Update all_combinations.py The original implementation had limitations in handling edge cases and certain input parameters, leading to potential RecursionError. * Update all_combinations.py Added checks to handle cases where n or k are negative or where k is greater than n. In such scenarios, the function now returns an empty list, avoiding invalid recursive calls. * Update error handling Added checks to handle cases where `n` or `k` are negative or where `k` is greater than `n`. In such scenarios, the function now returns an empty list, avoiding invalid recursive calls. * Update backtracking/all_combinations.py * Update all_combinations.py --------- Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 341559d commit d9a11a9

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

backtracking/all_combinations.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,22 @@ def generate_all_combinations(n: int, k: int) -> list[list[int]]:
2626
>>> generate_all_combinations(n=10, k=-1)
2727
Traceback (most recent call last):
2828
...
29-
RecursionError: maximum recursion depth exceeded
29+
ValueError: k must not be negative
3030
>>> generate_all_combinations(n=-1, k=10)
31-
[]
31+
Traceback (most recent call last):
32+
...
33+
ValueError: n must not be negative
3234
>>> generate_all_combinations(n=5, k=4)
3335
[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
3436
>>> from itertools import combinations
3537
>>> all(generate_all_combinations(n, k) == combination_lists(n, k)
3638
... for n in range(1, 6) for k in range(1, 6))
3739
True
3840
"""
41+
if k < 0:
42+
raise ValueError("k must not be negative")
43+
if n < 0:
44+
raise ValueError("n must not be negative")
3945

4046
result: list[list[int]] = []
4147
create_all_state(1, n, k, [], result)

0 commit comments

Comments
 (0)