Compute n-element combinations from a given list using dynamic programming. Args: * `elements`: The list of elements from which combinations will be generated. * `n`: The number of elements in each combination. Returns: A list of tuples, each representing a com
(elements: list[int], n: int)
| 1 | def subset_combinations(elements: list[int], n: int) -> list: |
| 2 | """ |
| 3 | Compute n-element combinations from a given list using dynamic programming. |
| 4 | |
| 5 | Args: |
| 6 | * `elements`: The list of elements from which combinations will be generated. |
| 7 | * `n`: The number of elements in each combination. |
| 8 | |
| 9 | Returns: |
| 10 | A list of tuples, each representing a combination of `n` elements. |
| 11 | |
| 12 | >>> subset_combinations(elements=[10, 20, 30, 40], n=2) |
| 13 | [(10, 20), (10, 30), (10, 40), (20, 30), (20, 40), (30, 40)] |
| 14 | >>> subset_combinations(elements=[1, 2, 3], n=1) |
| 15 | [(1,), (2,), (3,)] |
| 16 | >>> subset_combinations(elements=[1, 2, 3], n=3) |
| 17 | [(1, 2, 3)] |
| 18 | >>> subset_combinations(elements=[42], n=1) |
| 19 | [(42,)] |
| 20 | >>> subset_combinations(elements=[6, 7, 8, 9], n=4) |
| 21 | [(6, 7, 8, 9)] |
| 22 | >>> subset_combinations(elements=[10, 20, 30, 40, 50], n=0) |
| 23 | [()] |
| 24 | >>> subset_combinations(elements=[1, 2, 3, 4], n=2) |
| 25 | [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] |
| 26 | >>> subset_combinations(elements=[1, 'apple', 3.14], n=2) |
| 27 | [(1, 'apple'), (1, 3.14), ('apple', 3.14)] |
| 28 | >>> subset_combinations(elements=['single'], n=0) |
| 29 | [()] |
| 30 | >>> subset_combinations(elements=[], n=9) |
| 31 | [] |
| 32 | >>> from itertools import combinations |
| 33 | >>> all(subset_combinations(items, n) == list(combinations(items, n)) |
| 34 | ... for items, n in ( |
| 35 | ... ([10, 20, 30, 40], 2), ([1, 2, 3], 1), ([1, 2, 3], 3), ([42], 1), |
| 36 | ... ([6, 7, 8, 9], 4), ([10, 20, 30, 40, 50], 1), ([1, 2, 3, 4], 2), |
| 37 | ... ([1, 'apple', 3.14], 2), (['single'], 0), ([], 9))) |
| 38 | True |
| 39 | """ |
| 40 | r = len(elements) |
| 41 | if n > r: |
| 42 | return [] |
| 43 | |
| 44 | dp: list[list[tuple]] = [[] for _ in range(r + 1)] |
| 45 | |
| 46 | dp[0].append(()) |
| 47 | |
| 48 | for i in range(1, r + 1): |
| 49 | for j in range(i, 0, -1): |
| 50 | for prev_combination in dp[j - 1]: |
| 51 | dp[j].append((*prev_combination, elements[i - 1])) |
| 52 | |
| 53 | try: |
| 54 | return sorted(dp[n]) |
| 55 | except TypeError: |
| 56 | return dp[n] |
| 57 | |
| 58 | |
| 59 | if __name__ == "__main__": |
no test coverage detected