Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
2列出了python中的排列_Python_Algorithm_List - Fatal编程技术网

2列出了python中的排列

2列出了python中的排列,python,algorithm,list,Python,Algorithm,List,做一门课程,它要求这样做,但做任何事情,包括这样的事情,我被难住了。 问题如下。请解释并给出答案,以便理解 编写一个Python函数,接收两个列表并计算它们是否是彼此的排列。列表可以同时包含整数和字符串。 我们对排列的定义如下: •列表具有相同数量的元素 •列表元素在两个列表中出现的次数相同 如果列表不是彼此的排列,则函数返回False。 如果它们是彼此的排列,则函数返回一个元组,该元组由以下元素组成: •发生次数最多的元素 •该元素出现多少次 •出现次数最多的元素类型 如果两个列表都为空,则返

做一门课程,它要求这样做,但做任何事情,包括这样的事情,我被难住了。 问题如下。请解释并给出答案,以便理解

编写一个Python函数,接收两个列表并计算它们是否是彼此的排列。列表可以同时包含整数和字符串。 我们对排列的定义如下:

•列表具有相同数量的元素

•列表元素在两个列表中出现的次数相同

如果列表不是彼此的排列,则函数返回False。 如果它们是彼此的排列,则函数返回一个元组,该元组由以下元素组成:

•发生次数最多的元素

•该元素出现多少次

•出现次数最多的元素类型

如果两个列表都为空,则返回元组(无、无、无)。如果多个元素出现的次数最多,则可以返回其中任何一个

def is_list_permutation(L1, L2):

    '''

    L1 and L2: lists containing integers and strings
    Returns False if L1 and L2 are not permutations of each other. 
            If they are permutations of each other, returns a 
            tuple of 3 items in this order: 
            the element occurring most, how many times it occurs, and its type
    '''

    # Your code here
比如说,

•如果L1=['a','a','b']和L2=['a','b'],则is\U列表\U排列返回False

•如果L1=[1',b',1',c',c',1]和L2=['c',1',b',1,1,'c'],则is_list_置换返回(1,3,),因为整数1出现 最多3次,1的类型为整数(注意元组中的第三个元素不是字符串)。

您可以使用dictionary(
dict
)存储列表中项目的发生情况。下面是
O(n)
算法。这是最好的一种

你可以这样做

  • 首先做一些基本检查,比如两个列表的长度是否相同,是否为空 清单检查等

  • 使用哈希映射存储第一个列表的项到计数映射

  • 用第一个列表项的哈希值检查第二个列表
  • 代码

    def is_permutation(l1,l2):
        if len(l1) != len(l2):
            return False
        if len(l1) == 0:
            return (None,None,None)
        max_item = None
        max_count = 0
        d = dict()
        for i in l1:
            d[i] = d.get(i,0) + 1
            if d[i] > max_count:
                max_count += 1
                max_item = i
        for i in l2:
            d[i] = d.get(i,0) - 1
            if d[i] == -1:
                return False
        return (max_item,max_count,type(max_item))
    
    print ([1,2,2,"34"],["34",2,1]),is_permutation([1,2,2,"34"],["34",2,1])
    print ([],["34",2,1]),is_permutation([],["34",2,1])
    print ([],[]),is_permutation([],[])
    print ([1,2,2,"34",2],["34",2,2,2,1]),is_permutation([1,2,2,"34",2],["34",2,2,2,1])
    
    您可以使用字典(
    dict
    )来存储列表中项目的发生情况。下面是
    O(n)
    算法。这是最好的一种

    你可以这样做

  • 首先做一些基本检查,比如两个列表的长度是否相同,是否为空 清单检查等

  • 使用哈希映射存储第一个列表的项到计数映射

  • 用第一个列表项的哈希值检查第二个列表
  • 代码

    def is_permutation(l1,l2):
        if len(l1) != len(l2):
            return False
        if len(l1) == 0:
            return (None,None,None)
        max_item = None
        max_count = 0
        d = dict()
        for i in l1:
            d[i] = d.get(i,0) + 1
            if d[i] > max_count:
                max_count += 1
                max_item = i
        for i in l2:
            d[i] = d.get(i,0) - 1
            if d[i] == -1:
                return False
        return (max_item,max_count,type(max_item))
    
    print ([1,2,2,"34"],["34",2,1]),is_permutation([1,2,2,"34"],["34",2,1])
    print ([],["34",2,1]),is_permutation([],["34",2,1])
    print ([],[]),is_permutation([],[])
    print ([1,2,2,"34",2],["34",2,2,2,1]),is_permutation([1,2,2,"34",2],["34",2,2,2,1])
    

    以下是带有注释的代码,逐行解释:

    在is\u list\u置换函数中使用isPermutation作为辅助方法。这使得代码更容易阅读和更清晰

    L1 = [1, 'b', 1, 'c', 'c', 1]
    L2 = ['c', 1, 'b', 1, 1, 'c']
    
    
    def isPermutation(list1,list2):
     if len(list1) != len(list2):
       return False;  #two list does not have same length so impossible being permutation of each other
     for i in range(0, len(list1)):
       if list1.count(list1[i]) != list2.count(list1[i]):
         return False
    
    def is_list_permutation(list1,list2):
      if (isPermutation(list1,list2) == False): #use the above method isPermutation to check if they are permutation of each other
        return False #if not return false
      elif not list1:
        return (None, None, None)
      else:
        mostOccurItem = max(set(list1), key=list1.count)  
        numberOfTimes = list1.count(mostOccurItem)
        theType = type(mostOccurItem)
        return (mostOccurItem, numberOfTimes, theType)
    
    print(is_list_permutation(L1,L2))
    

    希望这对您有所帮助

    以下是代码,注释逐行解释:

    在is\u list\u置换函数中使用isPermutation作为辅助方法。这使得代码更容易阅读和更清晰

    L1 = [1, 'b', 1, 'c', 'c', 1]
    L2 = ['c', 1, 'b', 1, 1, 'c']
    
    
    def isPermutation(list1,list2):
     if len(list1) != len(list2):
       return False;  #two list does not have same length so impossible being permutation of each other
     for i in range(0, len(list1)):
       if list1.count(list1[i]) != list2.count(list1[i]):
         return False
    
    def is_list_permutation(list1,list2):
      if (isPermutation(list1,list2) == False): #use the above method isPermutation to check if they are permutation of each other
        return False #if not return false
      elif not list1:
        return (None, None, None)
      else:
        mostOccurItem = max(set(list1), key=list1.count)  
        numberOfTimes = list1.count(mostOccurItem)
        theType = type(mostOccurItem)
        return (mostOccurItem, numberOfTimes, theType)
    
    print(is_list_permutation(L1,L2))
    

    希望这有帮助

    问题归结为比较
    multiset
    s,Python multiset实现称为:


    问题归结为比较
    multiset
    s,Python multiset实现称为:


    不确定您的任务条款是否允许使用任何模块,但如果允许,则对于
    集合
    而言,它变得非常琐碎:

    from collections import Counter
    def is_list_permutation(l1,l2):
        c1 = Counter(l1)
        c2 = Counter(l2)
        if c1 != c2:
            return False
        elif len(c1) == 0:
            return (None, None, None)
        else:
            t = c1.most_common(1)[0]
            return t + (type(t[0]),)
    

    不确定您的任务条款是否允许使用任何模块,但如果允许,则对于
    集合
    而言,它变得非常琐碎:

    from collections import Counter
    def is_list_permutation(l1,l2):
        c1 = Counter(l1)
        c2 = Counter(l2)
        if c1 != c2:
            return False
        elif len(c1) == 0:
            return (None, None, None)
        else:
            t = c1.most_common(1)[0]
            return t + (type(t[0]),)
    

    我正在学习字典理解,它对这类问题非常有用:

    def is_list_permutation(L1, L2):
        '''
        L1 and L2: lists containing integers and strings
        Returns False if L1 and L2 are not permutations of each other. 
                If they are permutations of each other, returns a 
                tuple of 3 items in this order: 
                the element occurring most, how many times it occurs, and its type
        '''
        C1 = L1[:]
            try:
                for e in L2:
                    L1.remove(e)
                if len(L1) != 0:
                    return False
                elif len(C1) == 0:
                    return (None, None, None)
            except:
                return False
            else:
                D = {C1.count(e): e for e in C1} # Dictionary comprehension
                key = max([x for x in D.keys()]) # List comprehension
                return (D[key], key, type(D[key])) # voilà!
    

    我正在学习字典理解,它对这类问题非常有用:

    def is_list_permutation(L1, L2):
        '''
        L1 and L2: lists containing integers and strings
        Returns False if L1 and L2 are not permutations of each other. 
                If they are permutations of each other, returns a 
                tuple of 3 items in this order: 
                the element occurring most, how many times it occurs, and its type
        '''
        C1 = L1[:]
            try:
                for e in L2:
                    L1.remove(e)
                if len(L1) != 0:
                    return False
                elif len(C1) == 0:
                    return (None, None, None)
            except:
                return False
            else:
                D = {C1.count(e): e for e in C1} # Dictionary comprehension
                key = max([x for x in D.keys()]) # List comprehension
                return (D[key], key, type(D[key])) # voilà!
    

    实际上,您正在尝试比较
    multiset
    s,Python有一个调用它的multiset实现,您只需要比较multiset。实际上,您正在尝试比较
    multiset
    s,Python有一个调用它的multiset实现,您只需要比较multiset。我更新了isPermutation方法。以前它没有考虑比较“1”和“1”,但现在它应该可以正常工作了。我更新了isPermutate方法。以前它没有考虑比较“1”和“1”,但现在它应该可以正常工作了。