jeudi 1 juin 2023

How can I randomize a list of integers 1 to X in CircuitPython without duplicates?

I am creating a circuit python project and the code compiles fine but it isn't working the way I intend. This loop that I have is supposed to generate a non repeating list of integers 1 to X in a random order. It does that except 1 and 2 are always copied in there for some odd reason. Because this is in circuit python, I cannot use random.sample so thats why this is simple code but it still doesn't work.

Edit: I do need the list to end up as a list of strings instead of a list of Integers. I failed to make that clear.

station = 20

songs = []
loop = True
while loop == True:
    r=random.randint(1, station)
    if r not in songs:
        songs.append(str(r))
    if len(songs) == station:
        loop = False

Output: ['14', '3', '11', '20', '10', '17', '9', '5', '19', '17', '1', '6', '18', '1', '9', '15', '6', '11', '14', '8', '2']

In this case 2 isn't in there twice but 1 is. I just want an exact list of 1 - X randomized with no duplicates.




Aucun commentaire:

Enregistrer un commentaire