George Washingpound
George Washingpound

Reputation: 25

Recursively Checking for List Uniqueness in Python

I have a list of 100 numbers and I am trying to write a function to determine whether all of the numbers are unique (as they should be). My function is unique(lst) and it takes a list as an input and should return True if all the numbers in my list are unique. Oh and False otherwise, an example:

>>> unique([1, 2, 3])
True

>>> unique([2, 4, 3, 4])
False

I wrote this so far:

def unique(lst):
    if len(lst) == 1:
        return True
    else:
        if lst[0] in lst[1:]:
            return False
        if lst[1] in unique(lst[2:-1]):
            return False
        else:
            return True 

I'm having trouble recursively checking whether the numbers after lst[0] are unique. Can anyone tell me how to edit my code so it checks correctly?

Upvotes: 1

Views: 4700

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

You just need to keep recursively moving across the list, you don't need to return a boolean :

def unique(lst):
    if len(lst) == 1: # if a single element left, list has unique elements
        return True
    elif lst[0] in lst[1:]: # check if current element is in the remainder of the list
            return False
    else:
        return unique(lst[1:]) # move to next element

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117951

How about this?

def unique(lst):
    if len(lst) == 1:
        return True
    else:
        currentElement = lst[0]
        remaining = lst[1:]
        elementIsUnique = currentElement not in remaining
        recursive = unique(remaining)
        return elementIsUnique and recursive

>>> unique([1, 2, 3])
True

>>> unique([2, 4, 3, 4])
False

Upvotes: 4

Related Questions