Solved

easy way to get the second (third, ...)  largest number in python

Posted on 2015-01-22
1
142 Views
Last Modified: 2015-01-27
Hi experts,

Is there an easy way in Python to get the second, or the third largest number in an array? consider two cases, one is every number is different, the other case is there are possible duplicated numbers.

Looking at some similar from MS Excel as: large(A:A, 2) to get the second largest number in A column.

Thanks,
RDB
0
Comment
Question by:ResourcefulDB
1 Comment
 
LVL 25

Accepted Solution

by:
clockwatcher earned 500 total points
ID: 40565608
Here you go:

nth_largest = lambda l, nth: sorted(set(l))[-(nth if nth<=len(set(l)) and nth>=1 else 0)]
print(nth_largest( (9, 8, 8, 8, 9, 9, 9, 3, 3, 4), 2))   # return the second largest number in the list - 8

Open in new window


You didn't define what you want to happen if you ask for the 4th largest number but only have 3 unique numbers, I went with the smallest number.
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question