递归检查Python中的列表唯一性

时间:2014-10-23 21:50:00

标签: python list recursion unique

我有一个包含100个数字的列表,我正在尝试编写一个函数来确定所有数字是否都是唯一的(因为它们应该是)。我的函数是unique(lst),它将列表作为输入,如果列表中的所有数字都是唯一的,则应返回True。哦,如果不这样,一个例子:

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

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

到目前为止我写了这个:

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 

我在递归检查lst [0]之后的数字是否唯一时遇到了麻烦。谁能告诉我如何编辑我的代码以便正确检查?

2 个答案:

答案 0 :(得分:3)

这个怎么样?

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

答案 1 :(得分:1)

你只需要在列表中递归移动,你不需要返回一个布尔值:

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
相关问题