我试图创建一个函数,一个接一个地生成8个从1到8的随机数,并将它们添加到数组中,每次添加之前检查它们是否唯一。但是,它并没有像预期的那样工作,而且,虽然它创建了一个由8个元素组成的数组,但是这些数字并不都是唯一的。我的代码:
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
我认为问题发生在第10行的某个地方,因为程序似乎直接转到else
语句,但我不明白为什么会发生这种情况。你知道吗
此外,当我运行程序时,数组在打印时似乎总是重复相同的2或3个数字多次,我不知道这是否与已经存在的问题有关,但它可以帮助解释发生了什么。你知道吗
对于你想要的方式:
但有更好的方法,例如:
或者将上面提到的
return
更改为return random.sample(range(1, 9), 8)
,以获得更简洁的效果。你知道吗这里没有什么“随机”的。你所需要做的就是把数字1到8洗牌。你知道吗
相关问题 更多 >
编程相关推荐