0

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

Beans
  • 3
  • 2
  • 2
    You are iterating over the same list twice.. so you will ALWAYS detect a duplicate here as the element you are checking against exists in both iterations. There is an answer to this here: https://stackoverflow.com/a/5278151/7942856 – PacketLoss Feb 22 '21 at 01:38
  • 1
    assume list `a` is passed to your function. During the first execution of your outer loop `num1 = 9`, during the first execution of your inner loop `num2 = 9` thus returning false since `num1 = num2`. Also returning mid function like that will exit the function returning false stopping the for loop for continuing. It's probably better to return true or false after iterating over the list in this case. – Nikster Feb 22 '21 at 01:44

1 Answers1

1

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
yoonghm
  • 4,198
  • 1
  • 32
  • 48