Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình Python kiểm tra hai list có phần tử chung


Trong bài này dùng hai list nhập từ người dùng. Nhiệm vụ kiểm tra xem có phần tử chung hay không. Dùng kỹ thuật duyệt đơn giản: duyệt cả hai list và so sánh từng phần tử của list đầu với list 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 và B là hai list nhập */
Bước 1: Dùng biến c hiển thị kết quả.
Bước 2: Duyệt cả hai list, so sánh từng phần tử list 1 với list 2.
Bước 3: Nếu tìm thấy phần tử chung thì c = FOUND, ngược lại NOT FOUND.

Ví dụ mã

# Chương trình Python kiểm tra hai list có phần tử chung
def commonelement(A, B):
    c = "NOT FOUND"
    # Duyệt list 1
    for i in A:
        # Duyệt list 2
        for j in B:
            # Nếu có chung
            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))

Kết quả

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