Python |检查两个列表是否循环相同

给出两个列表,检查它们是否正确 循环地 相同与否。

null

Check whether two lists are circularly identical

例如:

Input : list1 = [10, 10, 0, 0, 10]
        list2 = [10, 10, 10, 0, 0]
Output : Yes
Explanation: yes they are circularly identical as when we write the list1
             last index to second last index, then we find it is circularly
             same with list1 
Input : list1 = [10, 10, 10, 0, 0]
        list2 = [1, 10, 10, 0, 0]
Output :No

方法1:使用列表遍历

使用 穿越 ,我们必须把清单翻一番。检查任意x(0<=n)到任意x+n,并与列表2进行比较,查看列表1和列表2是否相同,如果两者相同,则列表2循环相同。使用两个循环,检查此属性。第一个循环将从0运行到len(列表1),然后检查索引(x到x+n)是否与列表2相同,如果是,则返回true,否则返回false。

下面是上述方法的Python实现:

# python program to check if two
# lists are circularly identical
# using traversal
# function to check circularly identical or not
def circularly_identical(list1, list2):
# doubling list
list3 = list1 * 2
# traversal in twice of list1
for x in range ( 0 , len (list1)):
z = 0
# check if list2 == list1 curcularly
for y in range (x, x + len (list1)):
if list2[z] = = list3[y]:
z + = 1
else :
break
# if all n elements are same circularly
if z = = len (list1):
return True
return False
# driver code
list1 = [ 10 , 10 , 0 , 0 , 10 ]
list2 = [ 10 , 10 , 10 , 0 , 0 ]
list3 = [ 1 , 10 , 10 , 0 , 0 ]
# check for list 1 and list 2
if (circularly_identical(list1, list2)):
print ( "Yes" )
else :
print ( "No" )
# check for list 2 and list 3
if (circularly_identical(list2, list3)):
print ( "Yes" )
else :
print ( "No" )


输出:

Yes
No

方法2:使用列表切片

# python program to check if two
# lists are circularly identical
# using traversal
# function to check circularly identical or not
def circularly_identical(list1, list2):
# doubling list
list1.extend(list1)
# traversal in twice of list1
for i in range ( len (list1)):
# check if sliced list1 is equal to list2
if list2 = = list1[i: i + len (list2)]:
return True
return False
# driver code
list1 = [ 10 , 10 , 0 , 0 , 10 ]
list2 = [ 10 , 10 , 10 , 0 , 0 ]
list3 = [ 1 , 10 , 10 , 0 , 0 ]
# check for list 1 and list 2
if (circularly_identical(list1, list2)):
print ( "Yes" )
else :
print ( "No" )
# check for list 2 and list 3
if (circularly_identical(list2, list3)):
print ( "Yes" )
else :
print ( "No" )


输出:

Yes
No

方法3:使用map()函数

使用Python的内置函数 地图() 我们可以在一个步骤中完成这项工作,我们必须在一个字符串中映射list2,然后查看它是否存在于另一个字符串中的list1(2*list1)的两次映射中。

下面是上述方法的Python实现:

# python program to check if two
# lists are circularly identical
# using map function
# function to check circularly identical or not
def circularly_identical(list1, list2):
return ( ' ' .join( map ( str , list2)) in ' ' .join( map ( str , list1 * 2 )))
# driver code
list1 = [ 10 , 10 , 0 , 0 , 10 ]
list2 = [ 10 , 10 , 10 , 0 , 0 ]
list3 = [ 1 , 10 , 10 , 0 , 0 ]
# check for list 1 and list 2
if (circularly_identical(list1, list2)):
print ( "Yes" )
else :
print ( "No" )
# check for list 2 and list 3
if (circularly_identical(list2, list3)):
print ( "Yes" )
else :
print ( "No" )


输出:

Yes
No

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享