Program 23
Write a function called merge that takes two already sorted lists of possibly different lengths, and merges them into a single sorted list.
(a) Do this using the sort method. (b) Do this without using the sort method.
a) Do this using the sort method
def merge(l1,l2):
l=l1+l2
l.sort()
return l
l1=list(map(int,input("Enter the Sorted list 1:").split()))
l2=list(map(int,input("Enter the Sorted list 2:").split()))
s=merge(l1,l2)
print("After merge the list is:",s)
OUTPUT:
========= RESTART: D:\old\r19 lab-python\22.py ===============
Enter the Sorted list 1:1 4 6 8 9
Enter the Sorted list 2:2 6 8 9 90
After merge the list is: [1, 2, 4, 6, 6, 8, 8, 9, 9, 90]
without using the sort method
def merge_lists(L1, L2):
# When one of them is an empty list, returns the other list
if not L1:
return L2
elif not L2:
return L1
result = []
i = 0
j = 0
for k in range(len(L1) + len(L2)):
if L1[i] <= L2[j]:
result.append(L1[i])
if i < len(L1) - 1:
i += 1
else:
result += L2[j:] # When the last element in L1 is reached,
break # append the rest of L2 to result.
else:
result.append(L2[j])
if j < len(L2) - 1:
j += 1
else:
result += L1[i:] # When the last element in L2 is reached,
break # append the rest of L1 to result.
return result
l1=list(map(int,input("Enter the Sorted list 1:").split()))
l2=list(map(int,input("Enter the Sorted list 2:").split()))
s=merge_lists(l1,l2)
print("After merge the list is:",s)
Output:
============= RESTART: D:/old/r19 lab-python/22-2.py ==============
Enter the Sorted list 1:2 3 4 78
Enter the Sorted list 2:1 89 23 90
After merge the list is: [1, 2, 3, 4, 78, 89, 23, 90]
>>>
No comments:
Post a Comment