2つのソートされていないリストのソートされたマージされたリストを作成するPythonプログラム
ここでは、2つのユーザー入力リストが指定されており、2つのリストの要素はソートされていません。私たちのタスクは、これら2つのソートされていない配列をマージし、その後リストをソートすることです。
例
Input: A [] = {100, 50, 150}
B [] = {200, 30, 20}
Output: Merge List:{20, 30, 50, 100, 150, 200}
アルゴリズム
Step 1: first we create two user input list. Step 2: Final merge list size is (size of the first list + the size of the second list). Step 3: then sort two list using sort() method. Step 4: Merge two sorted list and store it into a third list. Step 5: Merging remaining elements of a[] (if any).Merging remaining elements of b[] (if any). Step 6: display merged sorted list.
サンプルコード
# Python program to merge two unsorted lists
# in sorted order
# Function to merge array in sorted order
def unsortedarray (a, b, res, n, m):
# Sorting a[] and b[]
a.sort()
b.sort()
# Merge two sorted arrays into 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): # Merging remaining
# elements of a[] (if any)
res[k] = a[i]
i += 1
k += 1
while (j < m): # Merging remaining
# elements of b[] (if any)
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(n)):
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],)
出力
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
-
ソートされたリストに要素を挿入するPythonプログラム
この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −リストが与えられたので、ソートされた順序を変更せずにリストに要素を挿入する必要があります 以下で説明するように、2つのアプローチがあります- アプローチ1:強引な方法 例 def insert(list_, n): # search for i in range(len(list_)): if list_[i] > n: index = i
-
2つのリストの違いをリストするPythonプログラム。
この問題では、2つのリストが与えられます。私たちのタスクは、2つのリストの違いを表示することです。 Pythonはset()メソッドを提供します。ここではこの方法を使用します。セットは、重複する要素がない順序付けられていないコレクションです。セットオブジェクトは、和集合、共通部分、差、対称差などの数学演算もサポートしています。 例 Input::A = [10, 15, 20, 25, 30, 35, 40] B = [25, 40, 35] Output: [10, 20, 30, 15] 説明 difference list = A - B アルゴリズム Step 1: Inp