python - 使用递归检查两个未排序列表的元素和长度是否相等

标签 python python-3.x list recursion

我正在尝试编写一个纯递归函数,如果两个未排序的列表长度相同且包含相同的元素,该函数将返回 True。我不允许使用任何迭代,只能使用递归。这是它应该做什么的示例:

>>> SameStuff(['Hello',1,2,3],[3,2,1,'Hello'])
True
>>> SameStuff(['HELLO',1,2,3],[3,'two',1,'Hello'])
False
>>> SameStuff([1,2],[])
False

我正在为递归函数的逻辑而苦苦挣扎,并且遗漏了一些元素。这是我拥有的:

def SameStuff(list1,list2):
    if len(list1)!=len(list2):
        return False
    if #some base case:
        #return True?
    if list1[0] in list2:
        return SameStuff(list1[1:],list2)
    else:
        return False

最佳答案

我认为您的大部分逻辑都在正确的位置。您只是错过了两者都为空的情况,到那时大概它们是不同(可能)顺序的相同列表!

使用 remove 函数可能效率不高,但从两个不同的无序列表中弹出相同的元素很棘手。

def SameStuff(l1, l2):
    if not l1 and not l2:
        return True

    if len(l1) != len(l2):
        return False

    last_element = l1[-1]
    if last_element not in l2:
        return False

    l1.remove(last_element)
    l2.remove(last_element)

    return SameStuff(l1, l2)

关于python - 使用递归检查两个未排序列表的元素和长度是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882880/

相关文章:

python - 在 Python 中删除列表的最后一个元素失败

Python:难以过滤掉包含某些子字符串的字符串

python - 如何在 For 循环 (Python) 的范围内添加 "i"

python - Python调用C函数的效率

Python Pandas key 错误 : 'the label is not in the [index]'

python-3.x - 保存 StandardScaler() 模型以用于新数据集

python - 使用 For 循环更改 DataFrame 列 (Pandas) 中的数据

python - numpy 数组列表到坐标点列表的转换

python - Keras:掩蔽和扁平化

vb.net - List.add 覆盖列表中以前的项目 VB.NET