Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import copy
- def get_max(lst, number):
- lst = copy.deepcopy(lst)
- if number == 1:
- return max(lst)
- number -= 1
- del lst[lst.index(max(lst)]
- return get_max(lst, number)
- print(get_max([1, 2, 3, 4, 5], 2))
- def get_2nd_max(s):
- max1 = s[0]
- max2 = s[1]
- if max2 > max1:
- max1, max2 = max2, max1
- i = 2
- while i < len(s):
- if s[i] > max2:
- max2 = s[i]
- if max2 > max1:
- max1, max2 = max2, max1
- i += 1
- return max2
- import random
- s = [random.randint(1, 100) for _ in range(10)]
- print(s) # пример, [31, 63, 29, 43, 77, 36, 45, 11, 71, 91]
- print(get_2nd_max(s)) # 77
- # Сортируем для проверки, смотрим второй элемент с конца:
- print(sorted(s)) # [11, 29, 31, 36, 43, 45, 63, 71, 77, 91]
- def get_2nd_max(s):
- max1, max2 = s[0], s[1]
- i = 2
- while i < len(s):
- if max2 > max1:
- max1, max2 = max2, max1
- if s[i] > max2:
- max2 = s[i]
- i += 1
- return min(max1, max2)
- def get_2nd_max_recursive(s):
- def get_2nd_max_recursive_inner(s, max1, max2, i=2):
- if i >= len(s):
- return min(max1, max2)
- if max2 > max1:
- max1, max2 = max2, max1
- if s[i] > max2:
- max2 = s[i]
- return get_2nd_max_recursive_inner(s, max1, max2, i+1)
- return get_2nd_max_recursive_inner(s, s[0], s[1], i=2)
Add Comment
Please, Sign In to add comment