簡體   English   中英

用遞歸Python列出相等性

[英]list equality with recursion Python

我正在嘗試編寫一個程序,使用遞歸來告訴2個列表是否完全相同,當列表不相同時它可以工作,但是當它們相同時,它給我一個錯誤,指出列表索引超出范圍。 我編寫它的方式不是直接比較列表(lst1 == lst2)。 我只是比較列表的單個元素和列表的長度。

def compare (lst1, lst2):
    if len(lst1) != len(lst2):
        return False
    if lst1[0] != lst2[0]:
        return False
    return compare(lst1[1:],lst2[1:])

例:

>>> compare(['ispython',1,2,3], ['isPYthon',1,2,3])
False
>>> compare(['ispython',1,2,3], [1,2,3])
False
>>> compare(['ispython',1,2,3], ['ispython',1,2,3])
True

您需要一個基本案例。 您的邏輯幾乎是正確的,它在遞歸上沒有出口。 如果您輸入空白列表會怎樣?

if len(lst1) != len(lst2):
    return False

每個列表的長度為0,因此不會在此處返回。

if lst1[0] != lst2[0]:
    return False

lst1[0]不存在, lst2[0]也不存在,這就是發生索引錯誤的地方。 嘗試添加以下內容:

if len(lst1) == 0 == len(lst2) == 0:
    return True

您錯過了一個案件。 比較完兩個列表的最后一個元素之后,您仍然調用compare(lst1[1:]...即使沒有剩余,因此下一個調用的lst1[0]在一個空列表中查找。

您需要檢查並在此之前return True

if len(lst1) == len(lst2) == 0:
    return True

嘗試這個:

def compare (lst1, lst2):
    if lst1 and lst2:
        if len(lst1) != len(lst2):
            return False
        if lst1[0] != lst2[0]:
            return False
        return compare(lst1[1:],lst2[1:])
    else:
        return True

暫無
暫無

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

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