Bug fix combinations (#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>
This commit is contained in:
moaldeen 2023-11-25 08:31:17 -05:00 committed by GitHub
parent 4151a13b57
commit 050b2a6e2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -26,9 +26,11 @@ def generate_all_combinations(n: int, k: int) -> list[list[int]]:
>>> generate_all_combinations(n=10, k=-1) >>> generate_all_combinations(n=10, k=-1)
Traceback (most recent call last): Traceback (most recent call last):
... ...
RecursionError: maximum recursion depth exceeded ValueError: k must not be negative
>>> generate_all_combinations(n=-1, k=10) >>> generate_all_combinations(n=-1, k=10)
[] Traceback (most recent call last):
...
ValueError: n must not be negative
>>> generate_all_combinations(n=5, k=4) >>> generate_all_combinations(n=5, k=4)
[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]] [[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]]
>>> from itertools import combinations >>> from itertools import combinations
@ -36,6 +38,10 @@ def generate_all_combinations(n: int, k: int) -> list[list[int]]:
... for n in range(1, 6) for k in range(1, 6)) ... for n in range(1, 6) for k in range(1, 6))
True True
""" """
if k < 0:
raise ValueError("k must not be negative")
if n < 0:
raise ValueError("n must not be negative")
result: list[list[int]] = [] result: list[list[int]] = []
create_all_state(1, n, k, [], result) create_all_state(1, n, k, [], result)