comparing values in a set

為{幸葍}努か 提交于 2019-12-11 16:14:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!