w3resource

Python: Find the three smallest integers from a given list of numbers using Heap queue algorithm


2. Three Smallest Integers

Write a Python program to find the three smallest integers from a given list of numbers using the heap queue algorithm.

Sample Solution:

Python Code:

import heapq as hq
nums_list = [25, 35, 22, 85, 14, 65, 75, 22, 58]
print("Original list:")
print(nums_list)
# Find three smallest values
largest_nums = hq.nsmallest(3, nums_list)
print("\nThree smallest numbers are:", largest_nums)

Sample Output:

Original list:
[25, 35, 22, 85, 14, 65, 75, 22, 58]

Three smallest numbers are: [14, 22, 22] 

Flowchart:

Python heap queue algorithm: Find the three smallest integers from a given list of numbers using Heap queue algorithm.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the three smallest integers from a list using heapq.nsmallest and print the result.
  • Write a Python function that takes a list and returns the three smallest unique values using a heap-based approach.
  • Write a Python script to extract the three lowest numbers from a list using heapq, then validate the output by comparing with an ascending sort.
  • Write a Python program to handle cases where the list has fewer than three unique elements when finding the three smallest integers using heapq.

Go to:


Previous: Write a Python program to find the three largest integers from a given list of numbers using Heap queue algorithm.
Next: Write a Python program to implement a heapsort by pushing all values onto a heap and then popping off the smallest values one at a time.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.