Python程序检查两个列表是否至少有一个公共元素
在这个问题中我们使用了两个用户输入列表。我们的任务是检查是否有任何共同元素。我们使用非常简单的遍历技术,遍历列表并检查第一个列表和第二个列表的每个元素。
示例
Input : A = [10, 20, 30, 50]B = [90, 80, 30, 10, 3]
Output : FOUND
Input : A = [10, 20, 30, 50]
B = [100,200,300,500]
Output : NOT FOUND
算法
commonelement(A,B)/* A and B are two user input list */
Step 1: First use one third variable c which is display the result.
Step 2: Traverse both the list and compare every element of the first list with every element of the second list.
Step 3: If common element is found then c display FOUND otherwise display NOT FOUND.
示例代码
# 要检查的 Python 程序输出结果# 如果两个列表至少有
# 一个元素共同
# 使用列表遍历
def commonelement(A, B):
c = "NOT FOUND"
# 遍历第一个列表
for i in A:
# 遍历第二个列表
for j in B:
# 如果一个共同
if i == j:
c="FOUND"
return c
return c
# 驱动程序代码
A=list()
B=list()
n1=int(input("Enter the size of the first List ::"))
print("Enter the Element of first List ::")
for i in range(int(n1)):
k=int(input(""))
A.append(k)
n2=int(input("Enter the size of the second List ::"))
print("Enter the Element of second List ::")
for i in range(int(n2)):
k=int(input(""))
B.append(k)
print("Display Result ::",commonelement(A, B))
Enter the size of the first List ::4Enter the Element of first List ::
2
1
4
9
Enter the size of the second List ::5
Enter the Element of second List ::
9
90
4
89
67
Display Result :: FOUND
Enter the size of the first List ::4
Enter the Element of first List ::
67
89
45
23
Enter the size of the second List ::4
Enter the Element of second List ::
1
2
3
4
Display Result :: NOT FOUND
以上是 Python程序检查两个列表是否至少有一个公共元素 的全部内容, 来源链接: utcz.com/z/322870.html