Jonathan Davidson - 1 month ago 8

Python Question

Consider the following code:

`for i in range(size-1):`

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

print((i,j))

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):

print((i,j))

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 :

```
n=10
l1=range(n)
for i in sample(l1,len(l1)):
l2=range(i,n)
for j in sample(l2,len(l2)):
print(i,j)
```

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
```