Does shuffle() produce uniform result ?

tooru honda tooru_honda at fast-mail.org
Sat Aug 25 23:30:45 EDT 2007


By incorporating Alex's code, I got another performance boost of 20%.  
It is mostly due to Alex's more efficient implementation of block random 
than my own version.

-tooru honda

Below is the code I have now:


from binascii import hexlify
from os import urandom

class rcRandomC(random.SystemRandom):

    def __init__(self):
        random.SystemRandom.__init__(self)

        def rand2():
            
            while True:
                randata = urandom(2*1024)
                for i in xrange(0, 2*1024, 2):
                    yield int(hexlify(randata[i:i+2]),16)    # integer 
in [0,65535]
                    
        self.rand2_M = rand2().next 


    # modified from random._randbelow
    def randrange(self,startN,stopN):

        """Choose a random integer from range(startN, stopN).
        widthN<=65536

        """

        widthN=stopN-startN


        left_over_N=65536%widthN
        upper_bound_N= 65535-left_over_N

        random_number=self.rand2_M()

        while random_number>upper_bound_N:

            random_number=self.rand2_M()

        r = random_number%widthN        
   
        return startN+r

    def shuffle(self, x):
        """x, random=random.random -> shuffle list x in place; return 
None.

        """

        randrange=self.randrange

        for i in reversed(xrange(1, len(x))):
            # pick an element in x[:i+1] with which to exchange x[i]
            j = randrange(0,i+1)
            x[i], x[j] = x[j], x[i]



More information about the Python-list mailing list