MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / generate_all_combinations

Function generate_all_combinations

backtracking/all_combinations.py:23–61  ·  view source on GitHub ↗

Generates all possible combinations of k numbers out of 1 ... n using backtracking. >>> generate_all_combinations(n=4, k=2) [[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

(n: int, k: int)

Source from the content-addressed store, hash-verified

21
22
23def generate_all_combinations(n: int, k: int) -> list[list[int]]:
24 """
25 Generates all possible combinations of k numbers out of 1 ... n using backtracking.
26
27 >>> generate_all_combinations(n=4, k=2)
28 [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
29 >>> generate_all_combinations(n=0, k=0)
30 [[]]
31 >>> generate_all_combinations(n=10, k=-1)
32 Traceback (most recent call last):
33 ...
34 ValueError: k must not be negative
35 >>> generate_all_combinations(n=-1, k=10)
36 Traceback (most recent call last):
37 ...
38 ValueError: n must not be negative
39 >>> generate_all_combinations(n=5, k=4)
40 [[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]]
49 >>> from itertools import combinations
50 >>> all(generate_all_combinations(n, k) == combination_lists(n, k)
51 ... for n in range(1, 6) for k in range(1, 6))
52 True
53 """
54 if k < 0:
55 raise ValueError("k must not be negative")
56 if n < 0:
57 raise ValueError("n must not be negative")
58
59 result: list[list[int]] = []
60 create_all_state(1, n, k, [], result)
61 return result
62
63
64def create_all_state(

Callers 1

Calls 1

create_all_stateFunction · 0.85

Tested by

no test coverage detected