This is a quick Python coding puzzle or brain teaser for educational and/or entertainment purposes. The challenge is quite simple but is useful for learning or refreshing your coding skills while exercising some logical thinking.
Objective
Write a Python function that returns the top n (highest) values from a list of numbers. For example, given a list 1, 3, 4, 6, 8, 9 the function should return (9, 8, 6) as the top 3 (highest) numbers. The code should be flexible enough to allow top 2, top 5, top 10, top 20 or whatever is needed. It should also gets the n value from the user (for top n numbers). If n is invalid, such as when it’s larger than the count of numbers provided or it’s negative or zero or blank, it should only show 1 highest number from the input.
Click Run on the widget below to run the solution.
Try to solve it yourself first. If you’re stumped, click here for the solution. Minimal error checking and exception handling is done in the code for brevity, but in a real-world application, you’d need more robust error checking on inputs.
Be sure to check out my Patreon page for downloads with more advanced apps, solutions, tips on Python, Excel, etc. here.