Rotating list in Python without collection.deque

I want to make a script. The program should get a list Lwith values ​​and a natural number N.
If N>0, list objects move steps to the Nleft.
If N<0, list objects move abs(N)to the right.
If the N=0list remains the same ...

For example: for N=1and L=[1,2,3,4,5]conclusion [2,3,4,5,1].
For the same list and N=-1output[5,1,2,3,4]

I really did it with help collection.deque, but I want to do it only with lists, for loop and "if".

I have a problem to figure out how to make objects move.

l = input("enter list:")
N = input("enter number of rotations:")
import collections
d = collections.deque(l)
d.rotate(-N)
print d
+4
6

:

def rotate(L, N):
    if not L or N % len(L) == 0:
        return L
    return L[N % len(L):] + L[:N % len(L)]

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

for N in range(-3, 4):
    print(rotate(L, N))

:

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

, list, , . deque.rotate(), , O(k), k - . , , deque.rotate() - .

+3

:

result = l[N % len(l):]+l[:N % len(l)]
+2

numpy, roll, :

import numpy as np

array = np.arange(1, 6)  # 1 to 5
print array
print np.roll(array, 0)
print np.roll(array, 2)
print np.roll(array, -2)
print np.roll(array, 17)

, :

[1 2 3 4 5]
[1 2 3 4 5]
[4 5 1 2 3]
[3 4 5 1 2]
[4 5 1 2 3]
+1

, Python 3 ( P2).

L = list(map(int, input("Enter numbers: ").split(" ")))
N = int(input("Enter how many rotations to perform: "))
print(L[N:] + L[:N])
+1

, ,

def reverse(nums, start, end):
    i = start
    j = end - 1
    while i < j:
        tmp = nums[i]
        nums[i] = nums[j]
        nums[j] = tmp
        i += 1
        j -= 1

def rotate(nums, n):
    if n == 0:
        return nums
    length = len(nums)
    if n < 0:
        n = length + n
    reverse(nums, 0, n)
    reverse(nums, n, length)
    reverse(nums, 0, length)
    return nums

>>> rotate([1, 2, 3, 4, 5], 1)
[2, 3, 4, 5, 1]
>>> rotate([1, 2, 3, 4, 5], -1)
[5, 1, 2, 3, 4]
0

!:) .

here is my solution for this question (given that I am making these scripts for the python basic course for biologists):

L = input('Enter list of numbers, please: ')
N = input('Enter how many places to rotate: ')
L1 = L[N:]
L2 = L[:N]
L = L1 + L2
print L
0
source

Source: https://habr.com/ru/post/1618381/


All Articles