Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

random

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.

like image 265
Ykwk Avatar asked Jan 22 '26 17:01

Ykwk


1 Answers

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.

like image 61
Prometheus Avatar answered Jan 25 '26 06:01

Prometheus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!