Computer >> Máy Tính >  >> Lập trình >> Python

Chương trình Python để kiểm tra xem hai danh sách có ít nhất một phần tử chung hay không

Trong bài toán này, chúng tôi sử dụng hai danh sách đầu vào của người dùng. Nhiệm vụ của chúng ta là kiểm tra xem có phần tử chung nào hay không. Chúng tôi sử dụng kỹ thuật duyệt rất đơn giản, duyệt qua cả danh sách và kiểm tra mọi phần tử của danh sách đầu tiên và danh sách thứ hai.

Ví dụ

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

Thuật toán

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.

Mã mẫu

# Python program to check  
# if two lists have at-least  
# one element common 
# using traversal of list 
  
def commonelement(A, B): 
   c = "NOT FOUND"

   # traverse in the 1st list 
   for i in A: 
      # traverse in the 2nd list 
      for j in B: 
         # if one common 
         if i == j: 
            c="FOUND"
            return c  
    return c 

# Driver code
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)) 

Đầu ra

Enter the size of the first List ::4
Enter 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