Test cases for all_combinations (#10633)

* [ADD] Test cases for all_combinations

* [DEL] documentation reverted b/c redundant

* Update all_combinations.py

---------

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
RaymondDashWu 2023-10-17 07:57:33 -07:00 committed by GitHub
parent ac3bd1032c
commit 72bd653e04
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,15 +1,40 @@
""" """
In this problem, we want to determine all possible combinations of k In this problem, we want to determine all possible combinations of k
numbers out of 1 ... n. We use backtracking to solve this problem. numbers out of 1 ... n. We use backtracking to solve this problem.
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!)))
Time complexity: O(C(n,k)) which is O(n choose k) = O((n!/(k! * (n - k)!))),
""" """
from __future__ import annotations from __future__ import annotations
from itertools import combinations
def combination_lists(n: int, k: int) -> list[list[int]]:
"""
>>> combination_lists(n=4, k=2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
"""
return [list(x) for x in combinations(range(1, n + 1), k)]
def generate_all_combinations(n: int, k: int) -> list[list[int]]: def generate_all_combinations(n: int, k: int) -> list[list[int]]:
""" """
>>> generate_all_combinations(n=4, k=2) >>> generate_all_combinations(n=4, k=2)
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
>>> generate_all_combinations(n=0, k=0)
[[]]
>>> generate_all_combinations(n=10, k=-1)
Traceback (most recent call last):
...
RecursionError: maximum recursion depth exceeded
>>> generate_all_combinations(n=-1, k=10)
[]
>>> 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]]
>>> from itertools import combinations
>>> all(generate_all_combinations(n, k) == combination_lists(n, k)
... for n in range(1, 6) for k in range(1, 6))
True
""" """
result: list[list[int]] = [] result: list[list[int]] = []
@ -34,13 +59,17 @@ def create_all_state(
current_list.pop() current_list.pop()
def print_all_state(total_list: list[list[int]]) -> None:
for i in total_list:
print(*i)
if __name__ == "__main__": if __name__ == "__main__":
n = 4 from doctest import testmod
k = 2
total_list = generate_all_combinations(n, k) testmod()
print_all_state(total_list) print(generate_all_combinations(n=4, k=2))
tests = ((n, k) for n in range(1, 5) for k in range(1, 5))
for n, k in tests:
print(n, k, generate_all_combinations(n, k) == combination_lists(n, k))
print("Benchmark:")
from timeit import timeit
for func in ("combination_lists", "generate_all_combinations"):
print(f"{func:>25}(): {timeit(f'{func}(n=4, k = 2)', globals=globals())}")