Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Randomize in tables
#4
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")
Reply


Messages In This Thread
Randomize in tables - by mariavol - Aug-15-2022, 07:46 AM
RE: Randomize in tables - by Pedroski55 - Aug-15-2022, 10:29 AM
RE: Randomize in tables - by mariavol - Aug-15-2022, 02:36 PM
RE: Randomize in tables - by deanhystad - Aug-15-2022, 09:23 PM
RE: Randomize in tables - by Pedroski55 - Aug-15-2022, 11:30 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020