w3resource

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


1. Three Largest Integers

Write a Python program to find the three largest 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 largest values
largest_nums = hq.nlargest(3, nums_list)
print("\nThree largest numbers are:", largest_nums)

Sample Output:

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

Three largest numbers are: [85, 75, 65]  

Flowchart:

Python heap queue algorithm: Find the three largest 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 largest integers from a list using heapq.nlargest and verify the result by comparing it with a sorted list.
  • Write a Python function that accepts a list and returns the three largest unique integers using a heap-based approach.
  • Write a Python script to extract the top three maximum values from a list using heapq and then remove them one by one, printing each removed value.
  • Write a Python program to use heapq to find the three largest numbers in a list containing both positive and negative integers and then display them in descending order.

Python Code Editor:

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

Previous: Python heap queue algorithm Exercise Home.
Next: Write a Python program to find the three smallest integers from a given list of numbers using Heap queue algorithm.

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.