如何以递归方式比较python中的2个列表(未排序,与顺序无关) [英] how to recursively compare 2 lists in python (unsorted, order-independent)

查看:79
本文介绍了如何以递归方式比较python中的2个列表(未排序,与顺序无关)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的最后一个问题是能够准确比较两个没有相同元素的相同大小的列表.除了列表方法len,del,index外,我不能使用任何内置的Python函数(即sort,compare,Counter).

The last issue I have is being able to accurately compare two lists of the same size that have no elements in common. I cannot use any built in Python functions (i.e., sort, compare, Counter) except for list methods len, del, index.

我的代码:

def SameStuff(l1, l2):
    if len(l1) <= 1 or len(l2) <= 1 or len(l1) != len(l2):
        if len(l1) == 0 or len(l2) == 0:   
            return len(l1) == len(l2)
        else:                    
            return len(l1) == len(l2) and l1[0] == l2[0]     
    else:
        if l1[0] == l2[0]:                                          
            return SameStuff(l1[1:], l2[1:])                 
        else:
            return SameStuff(l1, l2[1:]+[l2[0]]) 

推荐答案

    def SameStuff(l1, l2):
        if l1 == []: return l2 == []
        if len(l1) != len(l2): return False
        else: return SameStuff(l1[1:], [x for x in l2 if x != l1[0]])

这是独立工作的顺序.

以下版本还允许重复列表中的元素.

And the following version allows also repetitions of elements in the lists.

def SameStuff(l1, l2):
    if l1 == []: return l2 == []    
    elif len(l1) != len(l2): return False  
    elif l1[0] in l2: 
        i = l2.index(l1[0]) 
        return SameStuff(l1[1:], l2[:i] + l2[i+1:]) 
    else: return False

这篇关于如何以递归方式比较python中的2个列表(未排序,与顺序无关)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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