Ykwk
Ykwk

Reputation: 39

How to randomly select from a list over iterations yet choose every member of the list at least once?

I would like my code to iterate four times (or possibly larger) over a list with a length of 3 while visiting every number on the list at least once.

for i in range(4):
        rand_selection = random.choice([1, 0, -1])
        print(rand_selection)

In the above code, it will have a chance of not selecting every single item on the list. For example, it might not print -1 even once if it randomly happened to choose 1 1 0 1.

Thank you for your advice and help.

Upvotes: 3

Views: 102

Answers (1)

Prometheus
Prometheus

Reputation: 618

This solution feels like a scam but,

import random

lis = [1, 0, -1]
random.shuffle(lis)
print(lis+[random.choice(lis)])

Returns a list of 4 numbers which can be designated as your 4 choices.

Upvotes: 1

Related Questions