Advertisement
acclivity

pyFind2ndLargestInteger

Mar 12th, 2021 (edited)
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. # Return the 2nd largest integer element from a list (or the only element if only 1)
  2. # Return 9900 if the list is empty, or contains any non-integer values
  3. # Mike Kerry - 13-March-2021
  4.  
  5. def get_2nd_largest(inlist):
  6.     if not inlist:
  7.         return 9900         # List is empty, so return 9900
  8.     try:
  9.         v = sum(inlist)     # Try and compute the sum of all the list entries
  10.     except:
  11.         return 9900         # sum was not possible, therefore the list contained a non-integer or non-float
  12.     if isinstance(v, float):
  13.         return 9900         # The sum produced a float result, therefore the list contained at least one float value
  14.  
  15.     inlist.sort(reverse=True)       # Sort the list in reverse order
  16.     inlist.append(inlist[-1])       # duplicate the smallest element
  17.     return inlist[1]                # return the 2nd largest element
  18.  
  19. # Test data:
  20. tests = [1,2,3,4], [6, 8, 4, 4, 6], [53, 23], [13], \
  21.         [12, "notnumber", 23], \
  22.         [-11, -3, -15, -9, -16], [], [1, 2, 5.5]
  23.  
  24. for t in tests:
  25.     print(t, get_2nd_largest(t.copy()))
  26.  
  27. # results:
  28. # [1, 2, 3, 4] 3
  29. # [6, 8, 4, 4, 6] 6
  30. # [53, 23] 23
  31. # [13] 13
  32. # [12, 'notnumber', 23] 9900
  33. # [-11, -3, -15, -9, -16] -9
  34. # [] 9900
  35. # [1, 2, 5.5] 9900
  36.  
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement