I'm trying to create a function that, one by one, generates 8 random numbers from 1 to 8 and adds them to an array, checking if they are unique each time before adding them. However, it doesn't work as expected and, while it creates an array consisting of 8 elements, the numbers are not all unique. My code:
import random #Allows the program to generate random numbers
correctSequence = [] #Defines array
def generateSequence(correctSequence): #Defines function, passes array as parameter
selection = random.randint(1,8) #Creates a random number and adds it to the array so there is a starting point for the for loop (Ln 10)
correctSequence.append(str(selection))
while len(correctSequence) < 8: #The while loop will continue to run until the array consists of 8 objects
selection = random.randint(1,8) #Generates a random number
for i in range(len(correctSequence)): #Loops through each value in the array
if correctSequence[i] == selection: #This line checks to see if the value already exists in the array
print("Duplicate") #This line is meant to print "Duplicate" when a duplicate value is generated
else:
correctSequence.append(str(selection)) #If the value doesnt already exist in the array, it will be added
print("Valid") #This line is meant to print "Valid" when a unique value is generated and added to the array
return correctSequence
#Main body of program
generateSequence(correctSequence) #The function is called
print(correctSequence) #The array is printed
I think the problem occurs somewhere around line 10 as the program seems to go straight to the else
statement but I can't see why this would happen.
Additionally, when I run the program, the array, when printed, always seems to repeat the same 2 or 3 numbers multiple times, I don't know if this relates to the already existing issue but it could help to explain what's going on.