From 600d0e716c45affffa433b5d63cf2218b92bce80 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Mon, 25 Dec 2023 23:17:18 +0100 Subject: [PATCH] combinations_of_sum moved to new itertools module --- src/tools/itertools.py | 14 +++++++++++++- src/tools/tools.py | 18 ++---------------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/tools/itertools.py b/src/tools/itertools.py index 8e36214..d89b172 100644 --- a/src/tools/itertools.py +++ b/src/tools/itertools.py @@ -1,5 +1,5 @@ from math import factorial -from typing import Sized +from typing import Sized, Iterator def len_combinations(iterable: Sized, r: int) -> int: @@ -18,3 +18,15 @@ def len_permutations(iterable: Sized, r: int) -> int: return 0 else: return factorial(n) // factorial(n - r) + + +def 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 combinations_of_sum(total_sum - value, length - 1, min_value): + yield (value,) + permutation diff --git a/src/tools/tools.py b/src/tools/tools.py index 057c73c..3690fb4 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, Iterator +from typing import Any class Cache(dict): @@ -46,9 +46,7 @@ class Dict(dict): self[k] = Dict(self[k]) elif isinstance(self[k], list): for i in range(len(self[k])): - if isinstance(self[k][i], dict) and not isinstance( - self[k][i], Dict - ): + if isinstance(self[k][i], dict) and not isinstance(self[k][i], Dict): self[k][i] = Dict(self[k][i]) def update(self, other: dict, **kwargs): @@ -166,18 +164,6 @@ 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)