Использование функции в функции

Рейтинг: 0Ответов: 2Опубликовано: 21.08.2023

как в функцию:

def bubble_sort(the_list):
    is_sorted = False
    while not is_sorted:
        is_sorted = True
        for i in range(len(the_list)-1):
            if the_list[i] > the_list[i+1]:
                the_list[i], the_list[i+1] = the_list[i+1], the_list[i]
                is_sorted = False
    return the_list

вставить функцию:

def more_than(a,b, key=None):
    if key is not None:
        return key(a) > key(b)
    return a > b

Ответы

▲ 3

Решение "в лоб"

def bubble_sort(the_list, keyf):
    def more_than(a, b, key=None):
        if key is not None:
            return key(a) > key(b)
        return a > b

    is_sorted = False
    while not is_sorted:
        is_sorted = True
        for i in range(len(the_list) - 1):
            if more_than(the_list[i], the_list[i + 1], keyf):
                the_list[i], the_list[i + 1] = the_list[i + 1], the_list[i]
                is_sorted = False
    return the_list


lst = [5, 2, 1, -7, 9, 2, 3]
print(bubble_sort(lst, abs))
[1, 2, 2, 3, 5, -7, 9]
▲ 2

Например, через использование lambda:

def bubble_sort(the_list, compare_func):
    is_sorted = False
    while not is_sorted:
        is_sorted = True
        for i in range(len(the_list)-1):
            if compare_func(the_list[i], the_list[i+1]):
                the_list[i], the_list[i+1] = the_list[i+1], the_list[i]
                is_sorted = False
    return the_list

def more_than(a,b, key=None):
    if key:
        return key(a) > key(b)
    return a > b

the_list = list(range(10, -10, -1))
print(bubble_sort(the_list, lambda x,y: more_than(x, y)))
print(bubble_sort(the_list, lambda x,y: more_than(x, y, abs)))

Вывод:

[-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, 10]