Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 10 - Lists - Programming Exercises - Page 354: 10.26

Answer

code

Work Step by Step

# 10.26 (Merge two sorted lists) Write the following function that merges two sorted lists # into a new sorted list: # def merge(list1, list2): # Implement the function in a way that takes len(list1) + len(list2) comparisons. # Write a test program that prompts the user to enter two sorted lists and # displays the merged list. def merge(l1, l2): res = [] c1 = 0 c2 = 0 while c1 < len(l1) and c2 < len(l2): m1 = l1[c1] m2 = l2[c2] if m1 < m2: res.append(m1) c1 += 1 else: res.append(m2) c2 += 1 while c1 < len(l1): res.append(l1[c1]) c1 += 1 while c2 < len(l2): res.append(l2[c2]) c2 += 1 return res l1 = [int(x) for x in input("Enter list1: ").split()] l2 = [int(x) for x in input("Enyer list2: ").split()] res = merge(l1, l2) print(res)
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.