From ffcc1e14c056288dd1e661e3a6c4e33956e45abb Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Mon, 18 Dec 2023 09:12:34 +0100 Subject: [PATCH] NEW tools.list_combinations_of_sum() - returns all possible tuples with len [length}, containing integers summing up to {total_sum} --- src/tools/tools.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/tools/tools.py b/src/tools/tools.py index f1e67d9..057c73c 100644 --- a/src/tools/tools.py +++ b/src/tools/tools.py @@ -4,7 +4,7 @@ import os.path import sys from fishhook import hook from functools import wraps -from typing import Any +from typing import Any, Iterator class Cache(dict): @@ -166,6 +166,18 @@ def cache(func): return new_func +def list_combinations_of_sum(total_sum: int, length: int = None, min_value: int = 0) -> Iterator[tuple[int]]: + if length is None: + length = total_sum + + if length == 1: + yield (total_sum,) + else: + for value in range(min_value, total_sum + 1): + for permutation in list_combinations_of_sum(total_sum - value, length - 1, min_value): + yield (value,) + permutation + + @hook(list) def intersection(self, *args) -> list: ret = set(self).intersection(*args)