判断两个列表是否是彼此的循环排列

2024-06-16 08:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我被指派编写一个函数,接受两个列表,如果另一个列表是另一个列表的循环置换,则返回True。 我编写了一个函数,它接受两个列表以及第一个和最后一个位置之间的更改。之后,我编写了一个函数,该函数使用for循环调用第一个函数,如果每个i的值为True,则在循环结束时返回True。 我尝试运行代码时遇到了几个错误消息:

文件“C:/WinPython-64bit-3.5.2.2Qt5/settings/.spyder-py3/温度py“,第13行,循环 如果改变位置(lst1,lst2):

文件“C:/WinPython-64bit-3.5.2.2Qt5/settings/.spyder-py3/温度py“,第5行,改变位置 lst3[0]=lst4[长度(lst4)]

这是我的代码:

def change_position(lst3, lst4):
    if len(lst3) != len(lst4):
        print(False)
    else:
        lst3[0] = lst4[len(lst4)]


def cyclic(lst1, lst2):
    if len(lst1) != len(lst2):
        print(False)
    else:
        for i in range(len(lst1)):
            if change_position(lst1, lst2):
                print(True)
            else:
                print(False)
cyclic([1, 2, 3, 4], [4, 1, 2, 3])

有人知道我如何修复这个功能吗? 提前谢谢你的帮助。在


Tags: 文件函数代码falsetrue列表forlen
3条回答

无需重新排列列表,只需进行索引计算即可

def is_cyc_perm (list1, list2):
    if len (list1) == len (list2):
        for shift in range (len (list1)):
            for i in range (len (list1)):
                if list1 [i] != list2 [(i + shift) % len (list1)]:
                    break
            else:
                return True
        else:
            return False
    else:
        return False


print (is_cyc_perm ([8, 2, 5, 7], [8, 2, 5, 7]))
print (is_cyc_perm ([7, 8, 2, 5], [8, 2, 5, 7]))
print (is_cyc_perm ([2, 5, 7, 8], [8, 2, 5, 7]))
print (is_cyc_perm ([8, 5, 2, 7], [8, 2, 5, 7]))
print (is_cyc_perm ([7, 2, 5, 8], [8, 2, 5, 7]))
print (is_cyc_perm ([8, 2, 5, 3], [8, 2, 5, 7]))

列表索引以0开头,应使用范围(0,len(list)-1)。在

def change_position(lst3, lst4):
    if len(lst3) != len(lst4):
        print(False)
    else:
        lst3[0] = lst4[len(lst4)-1]


def cyclic(lst1, lst2):
    if len(lst1) != len(lst2):
        print(False)
    else:
        for i in range(len(lst1)-1):
            if change_position(lst1, lst2):
                print(True)
            else:
                print(False)

旋转双链接列表是一种使用指针的快速操作。如果有匹配的话,你可以尝试所有的旋转。在

collections模块还提供Counter,如果两个列表具有相同元素的相同计数,则可以使用它进行快速测试。它只是一个明显的长度相同的检查更强大的版本。在

import collections

def is_cyc_perm(seq1, seq2):
    mset1 = collections.Counter(seq1)
    mset2 = collections.Counter(seq2)
    if mset1 != mset2:
        return False

    size = len(seq1)
    deq1 = collections.deque(seq1)
    deq2 = collections.deque(seq2)
    for _ in range(size):
        deq2.rotate()
        if deq1 == deq2:
            return True
    return False

相关问题 更多 >