Skuteczny sposób obracania listy w Pythonie

Jaki jest najbardziej efektywny sposób obracania listy w Pythonie? Teraz mam coś takiego:

>>> def rotate(l, n):
...     return l[n:] + l[:n]
... 
>>> l = [1,2,3,4]
>>> rotate(l,1)
[2, 3, 4, 1]
>>> rotate(l,2)
[3, 4, 1, 2]
>>> rotate(l,0)
[1, 2, 3, 4]
>>> rotate(l,-1)
[4, 1, 2, 3]
Czy jest lepszy sposób?
 294
Author: jameshfisher, 2010-01-27

26 answers

A collections.deque jest zoptymalizowany do ciągnięcia i pchania na obu końcach. Mają nawet dedykowaną metodę rotate().

from collections import deque
items = deque([1, 2])
items.append(3)        # deque == [1, 2, 3]
items.rotate(1)        # The deque is now: [3, 1, 2]
items.rotate(-1)       # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3]
 311
Author: Ignacio Vazquez-Abrams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-08 19:27:06

A co z używaniempop(0)?

list.pop([i])

Usuń pozycję na danej pozycji na liście i zwróć ją. Jeśli Nie podano indeksu, a.pop() usuwa i zwraca ostatnią pozycję w lista. (Nawiasy kwadratowe wokół i w sygnaturze metody oznacza, że parametr jest opcjonalny, a nie że należy wpisywać kwadrat nawiasy na tej pozycji. Często zobaczysz tę notację w odniesienie do biblioteki Pythona.)

 91
Author: Jamgold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-08 13:04:16

Numpy może to zrobić za pomocą roll polecenie:

>>> import numpy
>>> a=numpy.arange(1,10) #Generate some data
>>> numpy.roll(a,1)
array([9, 1, 2, 3, 4, 5, 6, 7, 8])
>>> numpy.roll(a,-1)
array([2, 3, 4, 5, 6, 7, 8, 9, 1])
>>> numpy.roll(a,5)
array([5, 6, 7, 8, 9, 1, 2, 3, 4])
>>> numpy.roll(a,9)
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
 71
Author: Richard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-13 10:57:20

To zależy od tego, co chcesz, aby się stało, gdy to zrobisz:

>>> shift([1,2,3], 14)

Możesz zmienić swoje:

def shift(seq, n):
    return seq[n:]+seq[:n]

Do:

def shift(seq, n):
    n = n % len(seq)
    return seq[n:] + seq[:n]
 36
Author: jcdyer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 21:48:40

Najprostszy sposób, jaki mogę wymyślić:

a.append(a.pop(0))
 23
Author: Thijs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-16 14:30:35

Jeśli chcesz tylko iterować nad tymi zbiorami elementów, zamiast tworzyć oddzielną strukturę danych, rozważ użycie iteratorów do zbudowania wyrażenia generatora:

def shift(l,n):
    return itertools.islice(itertools.cycle(l),n,n+len(l))

>>> list(shift([1,2,3],1))
[2, 3, 1]
 15
Author: Phil H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-29 15:34:10

Tylko kilka uwag na temat czasu:

Jeśli zaczynasz od listy, l.append(l.pop(0)) jest najszybszą metodą, której możesz użyć. To może być pokazane z złożoności czasu sam:

  • deque.rotate is O (k) (K=liczba elementów)
  • Lista do konwersji deque to O (n)
  • lista.dodawanie i lista.pop to zarówno O (1)

Więc jeśli zaczynasz od deque obiektów, możesz deque.rotate() kosztem O(k). Ale jeśli punktem wyjścia jest lista, złożoność czasowa użycia deque.rotate() wynosi O (n). l.append(l.pop(0) jest szybszy Przy O(1).

Dla ilustracji, oto kilka przykładowych timingów na iteracjach 1M:]}

Metody wymagające konwersji typu:

  • deque.rotate with deque object: 0.12380790710449219 seconds (fastest)
  • deque.rotate z konwersją typu: 6.853878974914551 sekund
  • np.roll z nparray: 6.0491721630096436 sekund
  • np.roll z konwersją typu: 27.558452129364014 sekund

Lista metod wymienionych tutaj:

  • l.append(l.pop(0)): 0.32483696937561035 sekund (najszybszy)
  • "shiftInPlace": 4.819645881652832 seconds
  • ...

Użyty kod czasu jest poniżej.


Kolekcje.deque

Pokazujące, że tworzenie Deka z list to O (n):

from collections import deque
import big_o

def create_deque_from_list(l):
     return deque(l)

best, others = big_o.big_o(create_deque_from_list, lambda n: big_o.datagen.integers(n, -100, 100))
print best

# --> Linear: time = -2.6E-05 + 1.8E-08*n

Jeśli musisz utworzyć obiekty deque:

1M iteracji @ 6.853878974914551 sekund

setup_deque_rotate_with_create_deque = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
"""

test_deque_rotate_with_create_deque = """
dl = deque(l)
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_with_create_deque, setup_deque_rotate_with_create_deque)

Jeśli masz już obiekty deque:

1M iteracji @ 0.12380790710449219 sekund

setup_deque_rotate_alone = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
dl = deque(l)
"""

test_deque_rotate_alone= """
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_alone, setup_deque_rotate_alone)

Np.rolka

Jeśli potrzebujesz utworzyć nparrays

1M iteracji @ 27.558452129364014 sekund

setup_np_roll_with_create_npa = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
"""

test_np_roll_with_create_npa = """
np.roll(l,-1) # implicit conversion of l to np.nparray
"""

Jeśli masz już nparrays:

1M iteracji @ 6.0491721630096436 sekund

setup_np_roll_alone = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
npa = np.array(l)
"""

test_roll_alone = """
np.roll(npa,-1)
"""
timeit.timeit(test_roll_alone, setup_np_roll_alone)

"przesunięcie w miejscu"

Nie wymaga konwersji typu

1M iterations @ 4.819645881652832 seconds

setup_shift_in_place="""
import random
l = [random.random() for i in range(1000)]
def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l
"""

test_shift_in_place="""
shiftInPlace(l,-1)
"""

timeit.timeit(test_shift_in_place, setup_shift_in_place)

L. append(l. pop (0))

Nie wymaga konwersji typu

1M iteracji @ 0.32483696937561035

setup_append_pop="""
import random
l = [random.random() for i in range(1000)]
"""

test_append_pop="""
l.append(l.pop(0))
"""
timeit.timeit(test_append_pop, setup_append_pop)
 14
Author: Purrell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-04 11:11:31

Zależy to również od tego, czy chcesz przesunąć listę na miejsce (zmutować ją), czy też chcesz, aby funkcja zwróciła nową listę. Ponieważ, według moich testów, coś takiego jest co najmniej dwadzieścia razy szybsze niż Twoja implementacja, która dodaje dwie listy:

def shiftInPlace(l, n):
    n = n % len(l)
    head = l[:n]
    l[:n] = []
    l.extend(head)
    return l

W rzeczywistości nawet dodanie l = l[:] do góry, aby operować na kopii listy przekazanej jest nadal dwa razy szybsze.

Różne implementacje z pewnym czasem na http://gist.github.com/288272

 11
Author: keturn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 23:26:07

Zainteresowałem się tym i porównałem niektóre z proponowanych rozwiązań z perfplot (mój mały projekt).

Okazuje się, że

for _ in range(n):
    data.append(data.pop(0))

Jest zdecydowanie najszybszą metodą na małe przesunięcia n.

Dla większych n,

data[n:] + data[:n]
Nie jest źle.

Zasadniczo, perfplot wykonuje przesunięcie w celu zwiększenia dużych tablic i mierzy czas. Oto wyniki:

shift = 1:

Tutaj wpisz opis obrazka

shift = 100:

Tutaj wpisz opis obrazka


Kod do odtworzenia fabuły:

import numpy
import perfplot
import collections


shift = 100


def list_append(data):
    return data[shift:] + data[:shift]


def shift_concatenate(data):
    return numpy.concatenate([data[shift:], data[:shift]])


def roll(data):
    return numpy.roll(data, -shift)


def collections_deque(data):
    items = collections.deque(data)
    items.rotate(-shift)
    return items


def pop_append(data):
    for _ in range(shift):
        data.append(data.pop(0))
    return data


perfplot.save(
    "shift100.png",
    setup=lambda n: numpy.random.rand(n).tolist(),
    kernels=[list_append, roll, shift_concatenate, collections_deque, pop_append],
    n_range=[2 ** k for k in range(7, 20)],
    xlabel="len(data)",
)
 11
Author: Nico Schlömer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-18 09:38:49

Prawdopodobnie bardziej odpowiedni jest bufor ringowy. Nie jest to lista, chociaż jest prawdopodobne, że może zachowywać się wystarczająco jak lista dla Twoich celów.

Problem polega na tym, że wydajność zmiany na liście wynosi O(n), co staje się istotne dla wystarczająco dużych list.

Przesunięcie w buforze ringbuffer jest po prostu aktualizacją lokalizacji głowy, która jest O(1)

 4
Author: John La Rooy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 21:59:31

Dla niezmiennej implementacji, możesz użyć czegoś takiego:

def shift(seq, n):
    shifted_seq = []
    for i in range(len(seq)):
        shifted_seq.append(seq[(i-n) % len(seq)])
    return shifted_seq

print shift([1, 2, 3, 4], 1)
 4
Author: Bittercoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-06 15:08:12

Jeśli efektywność jest twoim celem, (cykle? pamięć?) może lepiej zajrzyj do modułu array: http://docs.python.org/library/array.html

Tablice nie mają narzutu list.

Jeśli chodzi o czyste listy, to, co masz, jest tak dobre,jak możesz mieć nadzieję.

 3
Author: recursive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-01-27 20:47:07

Myślę, że tego szukasz:

a.insert(0, x)
 3
Author: redreamality,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 09:46:01

Inna alternatywa:

def move(arr, n):
    return [arr[(idx-n) % len(arr)] for idx,_ in enumerate(arr)]
 2
Author: damio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-09 17:05:08
def solution(A, K):
    if len(A) == 0:
        return A

    K = K % len(A)

    return A[-K:] + A[:-K]

# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))

Na przykład, podane

A = [3, 8, 9, 7, 6]
K = 3

Funkcja powinna zwracać [9, 7, 6, 3, 8]. Wykonano trzy obroty:

[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]

Dla innego przykładu, podanego

A = [0, 0, 0]
K = 1

Funkcja powinna zwracać [0, 0, 0]

Given

A = [1, 2, 3, 4]
K = 4

Funkcja powinna zwracać [1, 2, 3, 4]

 2
Author: Rakesh Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-15 09:06:11

Jako punkt odniesienia traktuję ten model kosztów:

Http://scripts.mit.edu/ ~ 6.006 / fall07 / wiki / index. php?title=Python_Cost_Model

Twoja metoda cięcia listy i łączenia dwóch podlist to operacje liniowo-czasowe. Sugerowałbym użycie pop, który jest operacją stałą czasu, np.:

def shift(list, n):
    for i in range(n)
        temp = list.pop()
        list.insert(0, temp)
 1
Author: herrfz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-21 22:49:13

Nie wiem czy to jest "wydajne", ale też działa:

x = [1,2,3,4]
x.insert(0,x.pop())

EDIT: Witam ponownie, właśnie znalazłem duży problem z tym rozwiązaniem! Rozważmy następujący kod:

class MyClass():
    def __init__(self):
        self.classlist = []

    def shift_classlist(self): # right-shift-operation
        self.classlist.insert(0, self.classlist.pop())

if __name__ == '__main__':
    otherlist = [1,2,3]
    x = MyClass()

    # this is where kind of a magic link is created...
    x.classlist = otherlist

    for ii in xrange(2): # just to do it 2 times
        print '\n\n\nbefore shift:'
        print '     x.classlist =', x.classlist
        print '     otherlist =', otherlist
        x.shift_classlist() 
        print 'after shift:'
        print '     x.classlist =', x.classlist
        print '     otherlist =', otherlist, '<-- SHOULD NOT HAVE BIN CHANGED!'

Metoda shift_classlist() wykonuje ten sam kod co mój x.insert(0,x. pop())-rozwiązanie, otherlist jest listą niezależną od klasy. Po przekazaniu zawartości otherlist do MyClass.lista klas, wywołanie shift_classlist () zmienia również listę innych list:

Konsola Wyjście:

before shift:
     x.classlist = [1, 2, 3]
     otherlist = [1, 2, 3]
after shift:
     x.classlist = [3, 1, 2]
     otherlist = [3, 1, 2] <-- SHOULD NOT HAVE BIN CHANGED!



before shift:
     x.classlist = [3, 1, 2]
     otherlist = [3, 1, 2]
after shift:
     x.classlist = [2, 3, 1]
     otherlist = [2, 3, 1] <-- SHOULD NOT HAVE BIN CHANGED!

Używam Pythona 2.7. Nie wiem, czy to błąd, ale myślę, że bardziej prawdopodobne jest, że brakuje mi czegoś tutaj.

Czy ktoś z was wie, dlaczego tak się dzieje?
 1
Author: wese3112,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 06:33:24

Następująca metoda jest O (n) w miejscu ze stałą pamięcią pomocniczą:

def rotate(arr, shift):
  pivot = shift % len(arr)
  dst = 0
  src = pivot
  while (dst != src):
    arr[dst], arr[src] = arr[src], arr[dst]
    dst += 1
    src += 1
    if src == len(arr):
      src = pivot
    elif dst == pivot:
      pivot = src

Zauważ, że w Pythonie to podejście jest strasznie nieefektywne w porównaniu do innych, ponieważ nie może korzystać z natywnych implementacji żadnego z elementów.

 1
Author: DRayX,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-11 17:22:14

Mam coś podobnego. Na przykład przesunięcie o dwa...

def Shift(*args):
    return args[len(args)-2:]+args[:len(args)-2]
 1
Author: eyoeldefare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-13 18:19:35

Myślę, że masz najskuteczniejszy sposób

def shift(l,n):
    n = n % len(l)  
    return l[-U:] + l[:-U]
 1
Author: john ktejik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-23 21:17:46

Jaki jest przypadek użycia? Często nie potrzebujemy w pełni przesuniętej tablicy-potrzebujemy tylko dostępu do kilku elementów w przesuniętej tablicy.

Pobieranie plasterków Pythona to runtime O(k), gdzie k jest plasterkiem, więc rotacja plasterków to runtime N. polecenie deque rotation to również O (k). Stać nas na więcej?

Rozważ tablicę, która jest bardzo duża (powiedzmy, tak duża, że jej przecięcie byłoby obliczeniowo wolne). Alternatywnym rozwiązaniem byłoby opuszczenie oryginalnej tablicy sam i po prostu Oblicz indeks elementu, który istniałby w naszym pożądanym indeksie po jakimś przesunięciu.

Dostęp do przesuniętego elementu staje się zatem O(1).

def get_shifted_element(original_list, shift_to_left, index_in_shifted):
    # back calculate the original index by reversing the left shift
    idx_original = (index_in_shifted + shift_to_left) % len(original_list)
    return original_list[idx_original]

my_list = [1, 2, 3, 4, 5]

print get_shifted_element(my_list, 1, 2) ----> outputs 4

print get_shifted_element(my_list, -2, 3) -----> outputs 2 
 0
Author: Nick Lee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 23:53:37

Następujące kopie funkcji wysłane do templariusza, aby funkcja pop nie miała wpływu na oryginalną listę:

def shift(lst, n, toreverse=False):
    templist = []
    for i in lst: templist.append(i)
    if toreverse:
        for i in range(n):  templist = [templist.pop()]+templist
    else:
        for i in range(n):  templist = templist+[templist.pop(0)]
    return templist

Testowanie:

lst = [1,2,3,4,5]
print("lst=", lst)
print("shift by 1:", shift(lst,1))
print("lst=", lst)
print("shift by 7:", shift(lst,7))
print("lst=", lst)
print("shift by 1 reverse:", shift(lst,1, True))
print("lst=", lst)
print("shift by 7 reverse:", shift(lst,7, True))
print("lst=", lst)

Wyjście:

lst= [1, 2, 3, 4, 5]
shift by 1: [2, 3, 4, 5, 1]
lst= [1, 2, 3, 4, 5]
shift by 7: [3, 4, 5, 1, 2]
lst= [1, 2, 3, 4, 5]
shift by 1 reverse: [5, 1, 2, 3, 4]
lst= [1, 2, 3, 4, 5]
shift by 7 reverse: [4, 5, 1, 2, 3]
lst= [1, 2, 3, 4, 5]
 0
Author: rnso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-14 15:28:32

Jon Bentley w Perły programowania (kolumna 2) opisuje elegancki i wydajny algorytm obracania n - elementowego wektora x pozostawionego przez i pozycje:

Rozpatrzmy problem jako przekształcenie tablicy ab w tablicę ba, ale załóżmy również, że mamy funkcję odwracającą elementów w określonej części tablicy. Zaczynając od ab, mamy reverse a to get arb, reverse b to get arbr, a następnie odwrócić całe thing to get (arbr)r, czyli dokładnie ba. Daje to następujący kod dla rotacja:

reverse(0, i-1)
reverse(i, n-1)
reverse(0, n-1)

Można to przetłumaczyć na Python w następujący sposób:

def rotate(x, i):
    i %= len(x)
    x[:i] = reversed(x[:i])
    x[i:] = reversed(x[i:])
    x[:] = reversed(x)
    return x

Demo:

>>> def rotate(x, i):
...     i %= len(x)
...     x[:i] = reversed(x[:i])
...     x[i:] = reversed(x[i:])
...     x[:] = reversed(x)
...     return x
... 
>>> rotate(list('abcdefgh'), 1)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
>>> rotate(list('abcdefgh'), 3)
['d', 'e', 'f', 'g', 'h', 'a', 'b', 'c']
>>> rotate(list('abcdefgh'), 8)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> rotate(list('abcdefgh'), 9)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
 0
Author: Eugene Yarmash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-01 20:10:37

Dla listy X = ['a', 'b', 'c', 'd', 'e', 'f'] i żądanej wartości przesunięcia shift mniej niż długość listy , możemy zdefiniować funkcję list_shift() Jak poniżej

def list_shift(my_list, shift):
    assert shift < len(my_list)
    return my_list[shift:] + my_list[:shift]

Przykłady,

list_shift(X,1) returns ['b', 'c', 'd', 'e', 'f', 'a'] list_shift(X,3) zwraca ['d', 'e', 'f', 'a', 'b', 'c']

 0
Author: helcode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-02 04:48:56

Szukałem na miejscu rozwiązania tego problemu. To rozwiązuje cel W O (k).

def solution(self, list, k):
    r=len(list)-1
    i = 0
    while i<k:
        temp = list[0]
        list[0:r] = list[1:r+1]
        list[r] = temp
        i+=1
    return list
 0
Author: Ankit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-25 16:14:42

Jestem "old school" definiuję efektywność w najniższych opóźnieniach, czasie procesora i zużyciu pamięci, naszym nemezis są nadęte biblioteki. Więc jest dokładnie jeden właściwy sposób:

    def rotatel(nums):
        back = nums.pop(0)
        nums.append(back)
        return nums
 0
Author: Light Bringer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-26 00:35:29