Thursday, September 5, 2013

random failure

>>> random.choice({0:1, 2:3})
1
>>> random.choice({0:1, 2:3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty 
KeyError: 1

Alright pythonauts, why does this fail sometimes and succeed others? :-)

2 comments:

  1. Some pydestrians might learn from the answer :)

    ReplyDelete
  2. Because random.choice expects something that can be indexed by elements of range of its len. So range of len contains 0 and 1, 0th item is 1, but 1st item doesn't exist. Half the time it gives 1, other half it KeyErrors.

    ReplyDelete