I'm playing with 2D arrays to make a random sequence generator. I'm trying to generate 10 lists of 6 integers each, without replacement, inside a 2D array. The integers allowed are between 0 and 100. However, I keep getting list index out of range errors, and can't work out why. Here's my code:
import random
numbers = [i for i in range(100)]
picked = []
unpicked = []
lines = [[0 for x in range(6)] for j in range(10)]
for i in range(10):
for j in range(6):
unpicked = [x for x in numbers+picked if x not in picked]
lines[i][j] = unpicked[random.randint(0,99)]
picked.append(lines[i][j])
3 Answers 3
Your should shrink the size that random.randint can choose from. Based on your application, I think it should be
random.randint(0, len(unpicked)-1)
Another thing is that in the following line
unpicked = [x for x in numbers+picked if x not in picked]
you don't need numbers+picked. Just put numbers would be enough because numbers always have from 0 to 99.
3 Comments
unpicked = [x for x in lines[i]+picked if x not in picked] as I want to generate sequences without replacement. Also, random.randint(0, len(unpicked)-1) gives me an empty range for randrange() errorunpacked should be unpicked = [x for x in numbers if x not in picked] unpicked means what is in numbers but not in picked. Thus, it should be this way. I think now the second error will be resolved.I think you need something like this
import random
numbers = [i for i in range(100)]
picked = []
unpicked = []
lines = [[0 for x in range(7)] for j in range(11)]
for i in range(10):
for j in range(6):
#unpicked = [x for x in numbers+picked if x not in picked]
x = random.randint(0,99)
while(x in picked):
x = random.randint(0,99)
lines[i][j] = x
picked.append(lines[i][j])
your logic of picking number is getting out of index.
Hope this helps!
3 Comments
There is an easy way:
numbers = range(101) # 0 ~ 100 (include 100)
random.shuffle(numbers) # in place
pickup_num = 60
n = 6
picked = numbers[:pickup_num]
lines = [picked[i:i+n] for i in range(0, pickup_num, n)]
pickedgrows its size,unpickedwill get smaller and you userandint(0, 99)which might generate numbers that is bigger thanunpicked's size. Thus, an error is thrown.