Как заменить элемент в списке по индексу и сдвинуть наименьшее на начальную позицию?
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, заменить этот элемент по индексу, и сдвинуть наименьшее на начальную позицию.
Как так можно сделать?
Ответы (3 шт):
def f(lst, x):
for i in range(len(lst)):
if lst[i] < x:
lst[i] = x
break
lst.sort()
return lst
Воспользуйтесь модулем 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]
Вот так вот для непустых списков:
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]