سؤال

Below is a portion of code from a program I have written that is by all means pretty basic.

pc1 = random.choice(cards)
cca1 = random.choice(cards)
while (pc1 == cca1):
    cca1 = random.choice(cards)
ccb1 = random.choice(cards)
while (pc1 == ccb1) or (cca1 == ccb1):
    ccb1 = random.choice(cards)

pc1, cca1 and ccb1 are just names of variables, shortened for ease of use. What this portion of code does is try to take 3 entries from a dictionary named cards. It uses the while functions to ensure that the chosen cards are not the same; they will always be different.

This goes on until I have 9 unique variables from my dictionary of 52, and it works fine except for sometimes producing the following error:

Traceback (most recent call last):
  File "C:\Python33\Programs\Poker\1.0.py", line 231, in <module>
    ccc2 = random.choice(cards)
  File "C:\Python33\lib\random.py", line 252, in choice
    return seq[i]
KeyError: 0

The variable in the error above (ccc2) is just a continuation of the previously shown code, and the variable supposedly causing the error changes every time.

The error only occurs sometimes (sometimes the program runs fine, other times it shows the error), and the line it occurred on also changes with every appearance. I understand my code is inefficient but I'm really just looking to stop this error, and maybe some useful ideas/hints on how to improve.

Once again; does what its supposed to but unidentifiably returns the error mentioned at seemingly random times with a seemingly random site of cause.

Thanks in advance!

هل كانت مفيدة؟

المحلول

The way random.choice works is designed for sequences, not mappings. It picks indices, so will sometimes try cards[0], which evidently isn't a valid key. The reason that the error appears random is, of course, because it depends on the value picked by random!

You can fix this by explicitly choosing from a sequence:

random.choice(list(cards))

To improve your code more generally, note that random also includes sample:

rcards = random.sample(list(cards), 3) # pick three random cards

Note that in both cases, we randomly choose keys from the dictionary.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top