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

Chương trình Python tạo list merged đã sắp xếp từ hai list unsorted


Cho hai list nhập từ người dùng, các phần tử chưa sắp xếp. Nhiệm vụ merge hai list unsorted rồi sắp xếp list kết quả.

Ví dụ

Input: A[] = {100, 50, 150}
B[] = {200, 30, 20}
Output: Merge List: {20, 30, 50, 100, 150, 200}

Thuật toán

Bước 1: Tạo hai list nhập từ người dùng.
Bước 2: Kích thước list merge = size list 1 + size list 2.
Bước 3: Sắp xếp hai list dùng sort().
Bước 4: Merge hai list đã sắp xếp lưu vào list thứ ba.
Bước 5: Merge phần tử còn lại của a[] (nếu có) và b[] (nếu có).
Bước 6: Hiển thị list merged đã sắp xếp.

Ví dụ mã

# Chương trình Python merge hai list unsorted theo thứ tự sorted
def unsortedarray(a, b, res, n, m):
    # Sắp xếp a[] và b[]
    a.sort()
    b.sort()
    # Merge hai sorted array vào res[]
    i, j, k = 0, 0, 0
    while (i < n and j < m):
        if (a[i] <= b[j]):
            res[k] = a[i]
            i += 1
            k += 1
        else:
            res[k] = b[j]
            j += 1
            k += 1
    while (i < n):
        res[k] = a[i]
        i += 1
        k += 1
    while (j < m):
        res[k] = b[j]
        j += 1
        k += 1

# Driver code
A = list()
n = int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
    k = int(input(""))
    A.append(k)

B = list()
m = int(input("Enter the size of the Second List ::"))
print("Enter the Element of Second List ::")
for i in range(int(m)):
    k = int(input(""))
    B.append(k)

# Final merge list
res = [0 for i in range(n + m)]
unsortedarray(A, B, res, n, m)
print("Sorted merged list:")
for i in range(n + m):
    print(res[i], end=" ")

Kết quả

Enter the size of the First List: 4
Enter the Element of First List::
8
79
56
3
Enter the size of the Second List: 4
Enter the Element of Second List::
67
1
9
45
Sorted merged list:
1 3 8 9 45 56 67 79