Python 3:应用递归比较列表? [英] Python 3: applying recursion to compare lists?

查看:46
本文介绍了Python 3:应用递归比较列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下内容定义一个函数,该函数接受两个参数list_1和list_2,并按如下方式进行比较:如果list_1和list_2的长度不同,则返回False;如果list_1和list_2相同,则返回True;否则返回列表之间第一个不匹配元素的索引.

I'm trying to define a function with the following that takes two parameters, list_1 and list_2, and compares them as follows: it returns False if list_1 and list_2 have different lengths, True if list_1 and list_2 are identical, and otherwise returns the index of the first mismatched elements between the lists.

到目前为止,我有这个:

So far I have this:

if len(list_1) != len(list_2):
    return False
elif list_1 == list_2:
    return True
else:
    i = 0
    if list_1[i] == list_2[i]:
        return i
    else:
        i += 1
        compare_lists(list_1, list_2)

从逻辑上讲,当我再次调用该函数时,我一直重置为0.有谁知道我能克服这个问题吗?

Logically i keeps getting reset to 0 when I call the function again. Does anyone know how I can overcome this?

推荐答案

您必须将 i 工作变量向下传递给每个函数.

You must pass thei working variable down to each function.

此外,您不应该检查每个函数中的列表是否相等或长度是否不同,因为这会破坏递归的意义,因为 list_1 == list_2 语句会导致后面的"-the-scenes"for循环遍历两个列表.这会大大降低性能.

Also, you shouldn't check whether the lists are equal or if they are different lengths in every function as this defeats the point of the recursion as the list_1 == list_2 statement causes a "behind-the-scenes" for-loop to iterate over both lists. This would dramatically decrease performance.

相反,只需捕获当前索引超出列表之一的末尾的情况即可.在这种情况下,如果它们的长度相同,则可以返回 True ;否则,我们返回 False ,因为我们到达了一个的结尾,但没有到达另一个.

Instead just catch the case where your current index is past the end of one of the lists. In this case, if they are both the same lengths, then we can return True; otherwise we return False since we have reached the end of one but not the other.

在上述情况不适用于此函数调用的索引的情况下,我们只需检查索引处的元素是否相同即可.如果不是,我们将返回索引(索引将通过我们的父母传递给初始调用者).否则,我们返回使用相同列表但以递增索引( i + 1 )调用自己(孩子)的结果.

In the case where the above case does not apply to the index of this function call, we simply check whether the elements at our index are the same. If they are not, we return our index (which will get passed up through our parents to the initial caller). Otherwise we return the result of calling ourselves (a child) with the same lists, but with an incremented index (i + 1).

def compare_lists(list_1, list_2, i=0):
    l1 = len(list_1)
    l2 = len(list_2)
    if i >= l1 or i >= l2:
        return l1 == l2
    if list_1[i] != list_2[i]:
        return i
    return compare_lists(list_1, list_2, i+1)

可按预期工作:

>>> compare_lists([6,4,2], [6,4,2])
True
>>> compare_lists([6,4,2], [6,4,3])
2
>>> compare_lists([6,4,2], [6,4])
False

这篇关于Python 3:应用递归比较列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆