random.SystemRandom().randint() inefficient

Alan Bawden alan at csail.mit.edu
Wed Jul 27 14:42:55 EDT 2022


Cecil Westerhof <Cecil at decebal.nl> writes:

   Yes, I try to select a random element, but it has also to be removed,
   because an element should not be used more as once.

Instead of using pop to do that why not something like:

    def lazy_shuffle(seq):
        """
        Generate the elements of the given sequence in a random order.
        """
        # Delete the next line if you want to use a different version of
        # randrange:
        from random import randrange
        # Delete the next line if SEQ is already a mutable sequence and you
        # are willing to have it destroyed by this process:
        seq = list(seq)
        n = len(seq)
        while n:
            i = randrange(n)
            yield seq[i]
            n -= 1
            if i < n:
                seq[i] = seq[n]

-- 
Alan Bawden


More information about the Python-list mailing list