2

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!

7
  • Does the function need to be structured this way or can you change it? For example, can you change the condition for the while?
    – Galen
    Dec 8, 2017 at 3:04
  • 1
    With the code you have written, you do not need the else. If the condition x not in ax is not satisfied, execution will continue at the beginning of the while body. j will not be incremented and x will not be appended to ax.
    – Galen
    Dec 8, 2017 at 3:08
  • The while was in the templet code, and I think it is because the size of the array is nx, and that is something that could be changed by a user. We are using 21 for nx right now, but we want the code to work if we decided to change the size of the array. I didnt test much with using a for statement, but if it works, I will try it.
    – Ryan
    Dec 8, 2017 at 3:09
  • When I dont have an else statement, the code produces nothing and doesnt exit until I stop it.
    – Ryan
    Dec 8, 2017 at 3:11
  • 3
    You are using x as both the minimum for randint and the return value of randint. The first time this loop runs, your minimum is replaced by the return value of randint. Once the distance between the minimum and maximum passed to randint becomes less than nx, the loop will never terminate.
    – Galen
    Dec 8, 2017 at 3:14

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.