I am still in school and this is a lab question in the format the teacher wants. I want to fill an array with random integers, but no duplicates. The array needs to be a certain length, meaning that if the integer generated is already in the list, it needs to return to the random.randint(x, y) statement and do it again. (This is just a snippet of the code. ax is the array, nx = 21, x = 10, y = 40)
import random
def fill(ax,nx, x,y): # fill the list a with n random integers in the range x --- y inclusive BUT NO duplicates permitted THIS code NEEDS to be fixed
j = 0
while (j < nx): # populate the array using the while loop
x = random.randint(x, y) # Return a random integer .
if x not in ax:
ax.append(x)
j = j + 1
else:
??????
return ax
This is where I am stuck. There needs to be an else statement that returns to the beginning of the while loop if the integer generated is already in the list. I cannot figure it out. I've tried continue but that does nothing. The comments are from the teacher. I feel like he is suggesting using a goto statement, but that is highly frowned upon and not even in python. This is my first question posted so go gentle!
while
?else
. If the conditionx not in ax
is not satisfied, execution will continue at the beginning of thewhile
body.j
will not be incremented andx
will not be appended toax
.x
as both the minimum forrandint
and the return value ofrandint
. The first time this loop runs, your minimum is replaced by the return value ofrandint
. Once the distance between the minimum and maximum passed torandint
becomes less thannx
, the loop will never terminate.