Home > Software engineering >  How do I get randint,random.choice, or random.sample to pick a certain number for every nth choice?
How do I get randint,random.choice, or random.sample to pick a certain number for every nth choice?

Time:01-20

I am currently assigning actions to certain numbers because I think it will work best with my current code. Everything works perfectly this way as I get a random choice that then assigns that number to a variable which is then checked to produce an action. Only issue is I want certain numbers to be chosen with a span of 9 choices, for example I want the numbers 3,4 or 5 to be chosen 3 times within a span of 9 choices, all other numbers can be random. The 3 choices can be split among those three numbers (so 3 can be chosen 2 times and 5 once for example). Is there a way to do this?

Here is a fraction of my code that goes with my explanation. So basically, what I'm trying to get at is modifying the amount of times that x is equal to 3,4 or 5 within the for loop. But I don't want to choose when x is equal to those numbers myself. I don't want to put ("if item == frame9: x = 3") for example. So, I don't want to pick the time or iteration to set x equal to 3, but I want the program to choose 3, at least 3 times in the for loop. Is it possible to make a way that the program goes back to check the choices, and then changes them if not enough of them were 3? Sorry if this is a bit confusing, I'm still new to this. Appreciate the help!

frames = [frame1, frame2, frame3, frame4, frame5, frame6, frame7, frame8, frame9]

 for item in frames:
        x = randint(1, 16)

        if x == 1:
            d1 = Ds(1)
            letter_list.append("d1")

        elif x == 2:
            d2 = Ds(0, 1)
            letter_list.append("d2")

        elif x == 3:
            d3 = Ds(1, 1)
            letter_list.append("d3")

        elif x == 4:
            d4 = Ds(2)
            letter_list.append("d4")

        elif x == 5:
            d5 = Ds(0, 2)
            letter_list.append("d5")

CodePudding user response:

You can start with the numbers you want to always appear (let's say 3,4,5) put them in a list and fill the rest with random numbers, then use shuffle to randomize the order.

static = [random.choice([3,4,5]) for _ in range(3)]
random_numbers = static   [random.randint(1,16) for _ in range(len(frames) - len(static))]
random.shuffle(random_numbers) # to not always get the wanted numbers in the begining.
for x, item in zip(random_numbers, frames):
    # your loop
  • Related