3
chips = [400, 700, 900]
my_chips = 750

OUT: [700, 750, 900]

chips = [500, 900, 1200]
my_chips = 3000

OUT: [900, 1200, 3000]

Требуется проверить, если наша переменная my_chips больше одного из элементов в chips, заменить этот элемент по индексу, и сдвинуть наименьшее на начальную позицию.

Как так можно сделать?

2
  • chips отсортирован?
    – dIm0n
    15 сен 2020 в 13:35
  • @dIm0n да отсортирован
    – Lumo
    15 сен 2020 в 13:36

3 ответа 3

4

Воспользуйтесь модулем bisect:

This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!).


решение:

import bisect

def fun(lst, x):
    bisect.insort(lst, x)
    return lst[1:]

тесты:

In [57]: res = fun(chips, my_chips)

In [58]: res
Out[58]: [700, 750, 750, 900]

In [59]: res2 = fun([500, 900, 1200], 3000)

In [60]: res2
Out[60]: [900, 1200, 3000]
3
  • Да, но тут проблема в том, что удаление первого элемента делает линейным итоговый алгоритм энивей
    – dIm0n
    15 сен 2020 в 13:56
  • Проверил, это решение всё равно быстрее
    – dIm0n
    15 сен 2020 в 14:21
  • @dIm0n, я и не сомневался в способностях Python Core Team писать эффективный код ;) 15 сен 2020 в 14:26
3

Вот так вот для непустых списков:

import itertools


def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)


def modify_list(l, val):
    i = 0

    for a, b in pairwise(itertools.takewhile(lambda x: x < val, l)):
        l[i], l[i + 1] = b, a
        i += 1

    if l[i] < val:
        l[i] = val


chips = [400, 700, 900]
my_chips = 750

modify_list(chips, my_chips)
print(chips)  # [700, 750, 900]

chips = [500, 900, 1200]
my_chips = 3000

modify_list(chips, my_chips)
print(chips)  # [900, 1200, 3000]

chips = [500]
my_chips = 3000

modify_list(chips, my_chips)
print(chips)  # [3000]

chips = [4000]
my_chips = 3000

modify_list(chips, my_chips)
print(chips)  # [4000]
2
def f(lst, x):
    for i in range(len(lst)):
        if lst[i] < x:
            lst[i] = x
            break
    lst.sort()
    return lst
0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.