Aug-15-2022, 09:23 PM
(This post was last modified: Aug-15-2022, 09:23 PM by deanhystad.)
I would make combinations that match the requirements and randomly choose from those.
import random from itertools import combinations all_choices = {key: random.randint(1, 5) for key in "ABCDEFG"} def reduce(choices, count=1, total=float("inf")): return [ combo for combo in combinations(choices.items(), count) if sum(item[1] for item in combo) <= total ] # Get all combination of 5 choices who's sum <= 15 matching_choices = reduce(all_choices, 5, 15) if matching_choices: print( f"{random.choice(matching_choices)} from {len(matching_choices)} matching combinations" ) else: print("No combination meets the requirements")