Guest User

Untitled

a guest
Mar 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. import copy
  2.  
  3. def get_max(lst, number):
  4. lst = copy.deepcopy(lst)
  5. if number == 1:
  6. return max(lst)
  7. number -= 1
  8. del lst[lst.index(max(lst)]
  9. return get_max(lst, number)
  10.  
  11. print(get_max([1, 2, 3, 4, 5], 2))
  12.  
  13. def get_2nd_max(s):
  14. max1 = s[0]
  15. max2 = s[1]
  16. if max2 > max1:
  17. max1, max2 = max2, max1
  18.  
  19. i = 2
  20. while i < len(s):
  21. if s[i] > max2:
  22. max2 = s[i]
  23.  
  24. if max2 > max1:
  25. max1, max2 = max2, max1
  26.  
  27. i += 1
  28.  
  29. return max2
  30.  
  31. import random
  32.  
  33. s = [random.randint(1, 100) for _ in range(10)]
  34.  
  35. print(s) # пример, [31, 63, 29, 43, 77, 36, 45, 11, 71, 91]
  36.  
  37. print(get_2nd_max(s)) # 77
  38.  
  39. # Сортируем для проверки, смотрим второй элемент с конца:
  40. print(sorted(s)) # [11, 29, 31, 36, 43, 45, 63, 71, 77, 91]
  41.  
  42. def get_2nd_max(s):
  43. max1, max2 = s[0], s[1]
  44.  
  45. i = 2
  46. while i < len(s):
  47. if max2 > max1:
  48. max1, max2 = max2, max1
  49.  
  50. if s[i] > max2:
  51. max2 = s[i]
  52.  
  53. i += 1
  54.  
  55. return min(max1, max2)
  56.  
  57. def get_2nd_max_recursive(s):
  58. def get_2nd_max_recursive_inner(s, max1, max2, i=2):
  59. if i >= len(s):
  60. return min(max1, max2)
  61.  
  62. if max2 > max1:
  63. max1, max2 = max2, max1
  64.  
  65. if s[i] > max2:
  66. max2 = s[i]
  67.  
  68. return get_2nd_max_recursive_inner(s, max1, max2, i+1)
  69.  
  70. return get_2nd_max_recursive_inner(s, s[0], s[1], i=2)
Add Comment
Please, Sign In to add comment