问题
so my code currently generates a set with random integers between 1 and 200. It does this by using a while loop to add values to the set. What I'm having trouble doing is comparing values in a set to see if 2 values are duplicated. If they are, I want to return a bool value or an actual print statement saying they are duplicates. Similarly, I would want to stop generating a set if the duplicate is found within this
def abc(c):
a = 1
my = set()
while a <= c:
b = randrange(1, 200)
my.add(b)
a = a + 1
print(my)
回答1:
Test for membership with in:
while a <= c:
b = randrange(1, 200)
if b in my:
print('Duplicate random value generated')
my.add(b)
a = a + 1
Note that you could use a for loop with a range() call instead of a while loop here, to loop c times:
for i in range(c):
b = randrange(1, 200)
if b in my:
print('Duplicate random value generated')
my.add(b)
来源:https://stackoverflow.com/questions/19578747/comparing-values-in-a-set