Рекурсивный вызов Python для поиска максимального значенияPython

Программы на Python
Anonymous
Рекурсивный вызов Python для поиска максимального значения

Сообщение Anonymous »

Почему результат будет следующим:
49 53
41 53
87 53
87 53
23 87
...

Насколько я понимаю,
Первоначальный вызов как:
items[0] = 6
val2 = find_max([20, 8, 19, 56, 23, 87, 41, 49, 53])

Рекурсивный вызов:
val1 = 20
val2 = find_max([8, 19, 56, 23, 87, 41, 49, 53])

Код, как показано ниже:
items = [6, 20, 8, 19, 56, 23, 87, 41, 49, 53]

def find_max(items):
# breaking condition: last item in list? return it
if len(items) == 1:
return items[0]

# otherwise get the first item and call function
# again to operate on the rest of the list
val1 = items[0]
val2 = find_max(items[1:])

# perform the comparison when we're down to just two
if val1 > val2:
return val1
else:
return val2

# test the function
print(find_max(items))

49 53
41 53
87 53
87 53
23 87
56 87
19 87
8 87
20 87
6 87
87


Подробнее здесь: https://stackoverflow.com/questions/783 ... rsive-call

Вернуться в «Python»