[issue24567] random.choice IndexError due to double-rounding

Raymond Hettinger report at bugs.python.org
Sun Jul 12 00:52:36 CEST 2015


Raymond Hettinger added the comment:

FWIW, here are some variants (with differing degrees of brevity, clarity, and performance):

   def choice(self, seq):
        """Choose a random element from a non-empty sequence."""
        n = len(seq)
        i = int(self.random() * n)
        if i == n:
            i = n - 1
        return seq[i]

    def choice(self, seq):
        """Choose a random element from a non-empty sequence."""
        try:
            return seq[int(self.random() * len(seq))]                                                                                                         
        except IndexError:
            return seq[-1]

    def choice(self, seq):
        """Choose a random element from a non-empty sequence."""
        n = len(seq)
        return seq[min(int(self.random() * n), n-1)]

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue24567>
_______________________________________


More information about the Python-bugs-list mailing list