Python Exercise: Combine two given sorted lists using heapq module
Python heap queue algorithm: Exercise-20 with Solution
Write a Python program to combine two given sorted lists using heapq module.
Sample Solution:
Python Code:
from heapq import merge
nums1 = [1, 3, 5, 7, 9, 11]
nums2 = [0, 2, 4, 6, 8, 10]
print("Original sorted lists:")
print(nums1)
print(nums2)
print("\nAfter merging the said two sorted lists:")
print(list(merge(nums1, nums2)))
Sample Output:
Original sorted lists: [1, 3, 5, 7, 9, 11] [0, 2, 4, 6, 8, 10] After merging the said two sorted lists: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Flowchart:
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to print a heap as a tree-like data structure.
Next: Write a Python program to push three items into the heap and print the items from the heap.
What is the difficulty level of this exercise?
Test your Python skills with w3resource's quiz
Python: Tips of the Day
Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters)
Example:
def tips_anagram(s1, s2): _str1, _str2 = s1.replace(" ", ""), s2.replace(" ", "") return False if len(_str1) != len(_str2) else sorted(_str1.lower()) == sorted(_str2.lower()) print(tips_anagram("TRIANGLE", "INTEGRAL")) print(tips_anagram("anagram", "Nag a ram"))
Output:
True True
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework