samedi 26 novembre 2016

"ValueError: list.remove(x): x not in list", due to random numbers?

I'm writing a function to take a new card from a deck of cards, given that there are already some cards out of the deck.

def trekken(getrokken = []):
    import itertools
    import random

    getrokken = list(getrokken)
    kind = 'HCDS'
    value = '123456789XJQKA'
    deck = ["".join(card) for card in itertools.product(value,kind)]
    for i in range(0, len(getrokken)-1): deck.remove(getrokken[i])
    return(deck[(random.randint(1, len(deck)))])

When I use this for some examples a few times I sometimes get the error message:

line 16, in trekken print(deck[(random.randint(1, len(deck)))]) IndexError: list index out of range

For example with the following input:

trekken(['6H', '3C', '3D', '8C', 'AD', '9D', '7D', 'QC'])

Maybe not the first time, but after a few tries (max. 20) I always get this error message.




Aucun commentaire:

Enregistrer un commentaire