import functools import itertools import time from typing import Sequence, Generator, List, Optional def stopwatch(func): @functools.wraps(func) def inner_func(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) end = time.perf_counter() print(f"Function : {func.__name__}") print(f"Finished in : {(end - start):.10f}s") return result return inner_func @stopwatch def get_weight_combinations(weights: Sequence[int], outcome_weight: int) -> int: combinations = 0 for length in range(1, len(weights) + 1): for combination in itertools.combinations(weights, r=length): if sum(combination) == outcome_weight: combinations += 1 return combinations assert get_weight_combinations(weights=(1, 2, 3, 4), outcome_weight=3) == 2 assert get_weight_combinations(weights=(1, 2, 3, 3, 4), outcome_weight=7) == 4 assert get_weight_combinations((3, 9, 8, 4, 5, 7, 10), 15) == 4 @stopwatch def get_weight_combinations_generator( weights: Sequence[int], outcome_weight: int, sequence: Optional[List] = None, sequence_sum: int = 0 ) -> Generator[List[int], None, None]: if sequence is None: sequence = [] if sequence_sum == outcome_weight: yield sequence if sequence_sum >= outcome_weight: return for i, n in enumerate(weights): remaining = weights[i + 1:] yield from get_weight_combinations_generator(remaining, outcome_weight, sequence.append(n), sequence_sum + n) assert len(list(get_weight_combinations_generator(weights=(1, 2, 3, 4), outcome_weight=3))) == 2 assert len(list(get_weight_combinations_generator(weights=(1, 2, 3, 3, 4), outcome_weight=7))) == 4 assert len(list(get_weight_combinations_generator(weights=(3, 9, 8, 4, 5, 7, 10), outcome_weight=15))) == 4
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question