簡體   English   中英

遞歸檢查Python中的列表唯一性

[英]Recursively Checking for List Uniqueness in Python

我有一個包含100個數字的列表,我正在嘗試編寫一個函數來確定所有數字是否都是唯一的(應該是唯一的)。 我的函數是unique(lst) ,它將一個列表作為輸入,如果列表中的所有數字都是唯一的,則應返回True。 哦,否則為False,例如:

>>> 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]之后的數字是否唯一時遇到麻煩。 誰能告訴我如何編輯代碼以便正確檢查?

這個怎么樣?

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

您只需要在列表中遞歸移動,就不需要返回布爾值:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM