w3resource

Python: Get the two largest and three smallest items from a dataset


25. Extreme Items Extraction

Write a Python program to get the two largest and three smallest items from a dataset.

Sample Solution:

Python Code:

import heapq
h = [10, 20, 50, 70, 90, 20, 50, 40, 60, 80, 100]
print(heapq.nlargest(2,h))
print(heapq.nsmallest(3,h))

Sample Output:

[100, 90]
[10, 20, 20]

Flowchart:

Python heap queue algorithm: Get the two largest and three smallest items from a dataset.

For more Practice: Solve these Related Problems:

  • Write a Python program to extract the two largest and three smallest items from a dataset using heapq.nlargest and heapq.nsmallest.
  • Write a Python script to compute and print the two highest and three lowest numbers from a list using heap-based functions.
  • Write a Python program to find the extreme values in a list by using heapq to determine both the top two maximum and bottom three minimum values.
  • Write a Python function to return the two largest and three smallest items from an array and then verify the results by manual sorting.

Python Code Editor:

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

Previous: Write a Python program to create a heapsort, pushing all values onto a heap and then popping off the smallest values one at a time.
Next: Write a Python program to create a queue and display all the members and size of the queue.

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.