Home > database >  checking duplicates in list using while loop
checking duplicates in list using while loop

Time:10-04

I'm trying to check for duplicate numbers within a list using only while loops and if statements. For some reason it is returning True for the list [1, 2, 3, 4, 5, 6] and I can't figure out why.

def has_duplicates(xs):
count = 0
while count < len(xs) and len(xs) > 1:
    check = 1
    while check < len(xs):
        if xs[check] == xs[count]:
            return True
        else:
            check  = 1
    count  = 1
return False

CodePudding user response:

In your first algorithm you shouldn't assing to the check variable the value of 1. Otherwise on the second cycle of the loop both count and check will be 1 and you'll be comparing the element [1] of your list with itself, which will always return true.

Instead you should set the check variable to check = count 1. So that you never compare a value with itself.

CodePudding user response:

I get the correct output using your function. However, there are certainly easier ways to get the same result, as:

def has_duplic2(xs):
    return len(set(xs)) != len(xs)
  • Related