Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Return the 2nd largest integer element from a list (or the only element if only 1)
- # Return 9900 if the list is empty, or contains any non-integer values
- # Mike Kerry - 13-March-2021
- def get_2nd_largest(inlist):
- if not inlist:
- return 9900 # List is empty, so return 9900
- try:
- v = sum(inlist) # Try and compute the sum of all the list entries
- except:
- return 9900 # sum was not possible, therefore the list contained a non-integer or non-float
- if isinstance(v, float):
- return 9900 # The sum produced a float result, therefore the list contained at least one float value
- inlist.sort(reverse=True) # Sort the list in reverse order
- inlist.append(inlist[-1]) # duplicate the smallest element
- return inlist[1] # return the 2nd largest element
- # Test data:
- tests = [1,2,3,4], [6, 8, 4, 4, 6], [53, 23], [13], \
- [12, "notnumber", 23], \
- [-11, -3, -15, -9, -16], [], [1, 2, 5.5]
- for t in tests:
- print(t, get_2nd_largest(t.copy()))
- # results:
- # [1, 2, 3, 4] 3
- # [6, 8, 4, 4, 6] 6
- # [53, 23] 23
- # [13] 13
- # [12, 'notnumber', 23] 9900
- # [-11, -3, -15, -9, -16] -9
- # [] 9900
- # [1, 2, 5.5] 9900
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement