Jonathan Davidson Jonathan Davidson - 5 months ago 26
Python Question

How to go through a double for loop randomly in python

Consider the following code:

for i in range(size-1):
for j in range(i+1,size):

I need to go through this for-loop in a random fashion. I attempt to write a generator to do such a thing

def Neighborhood(size):
for i in shuffle(range(size-1)):
for j in shuffle(range(i+1), size):
yield i, j
for i,j in Neighborhood(size):

However, shuffle cannot be applied to whatever object range is. I do not know how to remedy the situation, and any help is much appreciated. I would prefer a solution avoid converting range to a list, since I need speed. For example, size could be on the order of 30,000 and i will do perform this for loop around 30,000 times.

I also plan to escape the for loop early, so I want to avoid solutions that incorporate shuffle(list(range(size)))

Answer Source

You can use random.sample.

The advantage of using random.sample over random.shuffle, is , it can work on iterators, so in :

  • Python 3.X you don't need to convert range() to list
  • In Python 2,X, you can use xrange
  • Same Code can work in Python 2.X and 3.X

Sample code :

for i in sample(l1,len(l1)):
    for j in sample(l2,len(l2)):

Edit :

As to why I put in this edit, go through the comments.

def Neighborhood(size):
    range1 = range(size-1)
    for i in sample(range1, len(range1)):
        range2 = range(i+1)
        for j in sample(range2, len(range2)):
            yield i, j
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download