Beans
Beans

Reputation: 3

Iterate through the same list twice to find no duplicate numbers

No count functions Here is my code below

*Testing lists below*
a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]
***

def is_unique(a_list): #returns true for no duplicate numbers #returns false other wise
    for num1 in a_list: #iterate through list once
        for num2 in a_list: #iterate thorough list twice
            if num1 == num2: #if num1 is the same as num2
                return False
            else:         #if num1 is not the same as num2
                return True

I want to show that the is_unique function can iterate through the same list twice and if the list has no duplicate numbers then it returns True Every time I run it I only get false, I can't get a True statement

I don't want to use sets

Upvotes: 0

Views: 1124

Answers (1)

yoonghm
yoonghm

Reputation: 4655

To solve the problem by iterate the list twice, one can do that:

a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]


def is_unique(a_list):
    i = 0
    for a in a_list:
        i = a_list.index(a, i)
        j = 0
        for b in a_list:
            j = a_list.index(b, j)
            if a == b and i != j:
                return False
    else:
        return True

print(is_unique(a))
print(is_unique(b))

The output:

False
True

The above code could be made more efficient by using enumerate():

def is_unique(a_list):
    for i, a in enumerate(a_list):
        for j, b in enumerate(a_list):
            if a == b and i != j:
                return False
    else:
        return True

Other methods to determine whether a given list has unique items:

Method 1: Convert the list to set, then compare number of items from the set and from the original list

a = [9, 4, 2, 3, 5, 9, 10]
b = [3, 4, -1, 9, 99, 12, 34]

def is_unique(a_list):
    return len(a_list) == len(set(a_list))

Method 2: Count the number of occurrence for each item in the list using list.count()

def is_unique(a_list):
    for a in a_list:
        if a_list.count(a) > 1:
            return False
    else:
        return True

Upvotes: 1

Related Questions