Python Array Rotation - python

So I am implementing a block swap algorithm in python.
The algorithm I am following is this:
Initialize A = arr[0..d-1] and B = arr[d..n-1]
1) Do following until size of A is equal to size of B
a) If A is shorter, divide B into Bl and Br such that Br is of same
length as A. Swap A and Br to change ABlBr into BrBlA. Now A
is at its final place, so recur on pieces of B.
b) If A is longer, divide A into Al and Ar such that Al is of same
length as B Swap Al and B to change AlArB into BArAl. Now B
is at its final place, so recur on pieces of A.
2) Finally when A and B are of equal size, block swap them.
The same algorithm has been implemented in C on this website - Array Rotation
My python code for the same is
a = [1,2,3,4,5,6,7,8]
x = 2
n = len(a)
def rotate(a,x):
n = len(a)
if x == 0 or x == n:
return a
if x == n -x:
print(a)
for i in range(x):
a[i], a[(i-x+n) % n] = a[(i-x+n) % n], a[i]
print(a)
return a
if x < n-x:
print(a)
for i in range(x):
a[i], a[(i-x+n) % n] = a[(i-x+n) % n], a[i]
print(a)
rotate(a[:n-x],x)
else:
print(a)
for i in range(n-x):
a[i], a[(i-(n-x) + n) % n] = a[(i-(n-x) + n) % n] , a[i]
print(a)
rotate(a[n-x:], n-x)
rotate(a,x)
print(a)
I am getting the right values at each stage but the recursive function call is not returning the expected result and I cannot seem to understand the cause. Can someone explain whats wrong with my recursion ? and what can be the possible alternative.

You can rotate a list in place in Python by using a deque:
>>> from collections import deque
>>> d=deque([1,2,3,4,5])
>>> d
deque([1, 2, 3, 4, 5])
>>> d.rotate(2)
>>> d
deque([4, 5, 1, 2, 3])
>>> d.rotate(-2)
>>> d
deque([1, 2, 3, 4, 5])
Or with list slices:
>>> li=[1,2,3,4,5]
>>> li[2:]+li[:2]
[3, 4, 5, 1, 2]
>>> li[-2:]+li[:-2]
[4, 5, 1, 2, 3]
Note that the sign convention is opposite with deque.rotate vs slices.
If you want a function that has the same sign convention:
def rotate(l, y=1):
if len(l) == 0:
return l
y = -y % len(l) # flip rotation direction
return l[y:] + l[:y]
>>> rotate([1,2,3,4,5],2)
[4, 5, 1, 2, 3]
>>> rotate([1,2,3,4,5],-22)
[3, 4, 5, 1, 2]
>>> rotate('abcdefg',3)
'efgabcd'
For numpy, just use np.roll
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.roll(a, 1)
array([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> np.roll(a, -1)
array([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])
Or you can use a numpy version of the same rotate above (again noting the difference in sign vs np.roll):
def rotate(a,n=1):
if len(a) == 0:
return a
n = -n % len(a) # flip rotation direction
return np.concatenate((a[n:],a[:n]))

A simple and shorthand syntax for array rotation in Python is
arr = arr[numOfRotations:]+arr[:numOfRotations]
Example:
arr = [1,2,3,4,5]
rotations = 4
then
arr = arr[4:]+arr[:4]
gives us
[5,1,2,3,4]

I found a problem that I needed Right and Left rotations for big values of k (where k is number of rotations), so, I implemented the following functions for any size of k.
Right Circular Rotation (left to the right: 1234 -> 4123):
def right_rotation(a, k):
# if the size of k > len(a), rotate only necessary with
# module of the division
rotations = k % len(a)
return a[-rotations:] + a[:-rotations]
Left Circular Rotation (right to the left: 1234 -> 2341):
def left_rotation(a, k):
# if the size of k > len(a), rotate only necessary with
# module of the division
rotations = k % len(a)
return a[rotations:] + a[:rotations]
Sources:
https://stackoverflow.com/a/46846544/7468664
https://stackoverflow.com/a/9457923/7468664

Do you actually need to implement the block swap or are you just looking to rotate the array? In python you can do CW and CWW rotations using
zip(*arr[::-1])
and
zip(*arr)[::-1]

I expect that when you pass a slice of a to your recursive call, you're not passing the same variable any more. Try passing a in its entirety and the upper / lower bounds of your slice as additional arguments to your function.
For instance consider this function:
def silly(z):
z[0] = 2
I just tried the following:
>>> z = [9,9,9,9,9,9]
>>> silly(z)
>>> z
[2, 9, 9, 9, 9, 9]
>>> silly(z[3:])
>>> z
[2, 9, 9, 9, 9, 9]
Where you can see the modification to the slice was not retained by the full array
Out of curiosity, what outputs do you get & what outputs do you expect?

you can use this code for left rotation in python array
import copy
def leftRotate(arr,n) :
_arr = copy.deepcopy(arr)
for i in range(len(arr)-n):
arr[i] = arr[i+n]
for j in range(n):
arr[(len(arr)-n)+j] = _arr[j]
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotateby = 3
leftRotate(arr,leftRotateby)
print arr
#output:: [4, 5, 6, 7, 1, 2, 3]

def leftRotation():
li = [int(x) for x in input().split()]
d = int(input())
ans = (li[d:]+li[0:d])
for i in ans:
print(i,end=' ')
print()
leftRotation()

def rotLeft(a, d):
lenght=len(a)
for j in range(0,d):
temp = a[0]
for i in range(lenght-1):
a[i] = a[i+1]
a[lenght-1] = temp
# Write your code here
return a
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
d = int(first_multiple_input[1])
a = list(map(int, input().rstrip().split()))
result = rotLeft(a, d)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()

Array Rotation:-
print("Right:1,Left:2")
op=int(input())
par=[1,2]
if op not in par:
print("Invalid Input!!")
else:
arr=list(map(int,input().strip().split()))
shift=int(input())
if op ==1:
right=arr[-shift:]+arr[:-shift]
print(right)
elif op==2:
left=arr[shift:]+arr[:shift]
print(left)
Ouput:-`
Right:1,Left:2
1
12 45 78 91 72 64 62 43
2
[62, 43, 12, 45, 78, 91, 72, 64]`

def rotate(nums=[1,2,3,4,5,6,7], k=3):
i=0
while i < k:
pop_item = nums.pop()
nums.insert(0, pop_item)
i += 1
return nums # [5,6,7,1,2,3,4]

If you are not supposed to use deque or slicing:
def rotate(array: List[int], k: int) -> List[int]:
# loop through the array from -k to array_size - k
return [array[i] for i in range(-k, len(array) - k)]

def rotate(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
result = []
if len(nums) <= 1 : return nums
if k > len(nums): k = K % len(nums)
for i in range(k):
result.insert(0,nums[-1])
nums.pop()
nums = result + nums
return nums

Here, I've used the method of swapping using a temporary variable to rotate an array. As an example, an array 'a' of size 5 is considered. Two variables 'j' and 'i' are used for outer and inner loop iterations respectively. 'c' is the temporary variable. Initially, the 1st element in the array is swapped with the last element in the array i.e a=[5,2,3,4,1]. Then, the 2nd element is swapped with the current last element i.e in this case 2 and 1. At present, the array 'a' would be a=[5,1,3,4,2]. This continues till it reaches the second last element in the array. Hence, if the size of the array is n (5 in this case), then n-1 iterations are done to rotate the array. To enter the no of times the rotation must be done, m is given a value with which the outer loop is run by comparing it with the value of j.
Note: The rotation of array is towards the left in this case
a=[1,2,3,4,5]
n=len(a)
m=int(input('Enter the no of rotations:'))
j=0
while(j<m):
i=0
while(i<n):
c=a[i]
a[i]=a[n-1]
a[n-1]=c
i=i+1
j=j+1
print(a)

Related

For loop in function to move the item of the list

I want to move the negative numbers to the end of the list until I encounter the positive number.
List:
a=[-1,-2,2,3,4,-5]
The result i want:
[-2, 2, 3, 4, -5, -1]
[2, 3, 4, -5, -1, -2]
My function:
def f1(A):
for i in A:
if i>=0:
break
if 'Z' not in globals() or 'Z' not in locals():
X=A
X1=X[0]
X.remove(X1)
X.append(X1)
Z=X
else:
X=Z
X1=X[0]
X.remove(X1)
X.append(X1)
Z=X
print(Z)
a=[-1,-2,2,3,4,-5]
print (f1 (a))
But the result
[-2, 2, 3, 4, -5, -1]
None
can we solve it with this function?
It's not a for loop, but:
>>> def shift(lst):
... while lst[0] < 0:
... lst = lst[1:] + [lst[0]]
... return lst
...
>>> a
[-1, -2, 2, 3, 4, -5]
>>> b = shift(a)
>>> b
[2, 3, 4, -5, -1, -2]
def f1(a):
a = a.copy()
while True:
i = a[0]
if i < 0:
a.append(i)
a = a[1:]
print(a)
else:
return a
while A[0] < 0: # While the list still begins with negative values
A.append(A.pop(0)) # Rotate left
This should work. For the explanation look at the comments.
What's more your function f1 doesn't have a returned value, so:
print(f1(a))
doesn't produce any output (only None, since there's no returned value)
Since in Python the lists are "passed by reference", you can do something like this:
while A[0] < 0:
...
return A # The list is already edited in global scope BUT doing this you allow the print statement above
You fell into one of python's traps. If A is a list and you do X=A, you do not get a new list, you just get a new name. Anything you do to list X will be done to list A and visa versa. So when you change list X you change list A
which is the list you are looping over. Do not modify the thing you are looping over. To get a copy of a list use X=A.copy(). Now you can modify X without changing A.
You asked to move the negative numbers to the end of the list a until encountering the first positive number. To actually move them in your list, meaning to "mutate" the list in place, you could do something like this:
def rotateInPlaceToFirstPositive(a):
n = len(a)
p = 0
while p < n and a[p] < 0:
p += 1
if p < n:
b = a[:p]
for i in range(n - p):
a[i] = a[i + p]
for i in range(p):
a[n - p + i] = b[i]
You can use this function like this:
a = [-1,-2,2,3,4,-5]
rotateInPlaceToFirstPositive(a)
print(a)
# prints: [2, 3, 4, -5, -1, -2]
However, if you prefer to leave a unchanged and return a separate list that has the desired result, you can just do this:
def rotateToFirstPositive(a):
n = len(a)
p = 0
while p < n and a[p] < 0:
p += 1
if p < n:
a = a[p:] + a[:p]
return a
Now, you will see this behavior when you call the function:
a = [-1,-2,2,3,4,-5]
print(rotateToFirstPositive(a))
# prints: [2, 3, 4, -5, -1, -2]

TypeError when Assigning Slice: "can only assign an iterable"

I'm writing recursive code to reverse a list in-place. This is what I have, but the code fails at assigning the slice to the input list, giving the error 'NoneType' object is not iterable:
def reverse(a):
if len(a) == 1:
return
temp = a[0]
a[0] = a[-1]
a[-1] = temp
a[1:-1] = reverse(a[1:-1])
return a
I have read that slices are not objects, so I attempted to use list() and range() to convert the returned slice, but by doing that, I still get the same error. Is there a way of assigning a slice to another slice of an array?
All your problem is return which sends None and gives 'NoneType' object is not iterable
You need return a. And rest of code start working.
BTW: You could use <= 1 instead of == 1 to work with empty list too.
def reverse(a):
if len(a) <= 1: # <-- `<=` to work with empty list
return a # <-- has to return `a`
temp = a[0]
a[0] = a[-1]
a[-1] = temp
#a[0], a[-1] = a[-1], a[0]
a[1:-1] = reverse(a[1:-1])
return a
# --- tests ---
print(reverse([1,2,3,4,5]))
print(reverse([1]))
print(reverse([]))
EDIT: To replace elements you can also use
a[0], a[-1] = a[-1], a[0]
EDIT: Using slice to create list with single element and list + list to join lists you can do:
def reverse(a):
if len(a) <= 1:
return a
return a[-1:] + reverse(a[1:-1]) + a[:1]
EDIT: You can even write it as lambda function (if you like functional programming which often uses recursion)
reverse = lambda a: a if len(a) <= 1 else a[-1:] + reverse(a[1:-1]) + a[:1]
# --- tests ---
print(reverse([1,2,3,4,5]))
print(reverse([1,2,3,4]))
print(reverse([1]))
print(reverse([]))
Reverse in-place
We will just keep on swapping start and end of list till both of them meet
def reverse(a,start=0,end=len(a)-1):
if start==end:return
a[start],a[end] = a[end],a[start]
reverse(a,start+1,end-1)
# return a # if it is inplace no need to return
a = [1,2,3,4,5]
reverse(a)
print(a)
[5, 4, 3, 2, 1]
I guess maybe this algorithm would be a bit closer to what you have in mind:
Here we are passing an index to the function you've already designed.
We would then increment that index using (-~index or simply index + 1).
def reverse(a, index=0):
if len(a) == 0:
return []
if len(a) == 1:
return a
if index == len(a) - 1:
return a
temp = a[0]
a[0] = a[-1]
a[-1] = temp
return reverse(a, index + 1)
print(reverse([1, 2, 3, 5, 6, 7, 8, 9]))
print(reverse([100, 90, -10, 1200, 1, 2, 3, 5, 6, 7, 8, 9]))
The three statements that you already have in your code are much more "algorithmic" (in all languages) than using Python's swap (a, b = b, a):
temp = a[0]
a[0] = a[-1]
a[-1] = temp
Output
[9, 2, 3, 5, 6, 7, 8, 1]
[9, 90, -10, 1200, 1, 2, 3, 5, 6, 7, 8, 100]

Replace climbing sequence with its average

I have a random list like this
X = [0, 1, 5, 6, 7, 10, 15]
and need to find and replace every climbing sequence with its average.
In the end it should look like this:
X = [0, 6, 10, 15] #the 0 and 1 to 0; and the 5,6,7 to 6
I tried to find the sequence by subtracting the second value from the first like this:
y = 0
z = []
while X[y +1] -X[y] == 1:
z.append(X[y])
y = y +1
And now I dont know how to delete for example 5,6 and 7 and replace it with the average 6.
You can use itertools.groupby on the list with a key function that returns each item's difference with an incremental counter:
from itertools import groupby, count
from statistics import mean
X = [0, 1, 5, 6, 7, 10, 15]
c = count()
X = [int(mean(g)) for _, g in groupby(X, key=lambda i: i - next(c))]
X becomes:
[0, 6, 10, 15]
You can iterate and group in the same list each climbing sequence for then taking the mean.
>>> res = [[x[0]]]
>>> for i in range(1, len(x)):
... if x[i] == x[i-1] + 1:
... res[-1].append(x[i])
... else:
... res.append([x[i]]
>>> res
[[0, 1], [5, 6, 7], [10], [15]]
>>> [int(sum(l)/len(l)) for l in res]
[0, 6, 10, 15]
Here's a starting technique: make a new list that's the difference of adjacent elements in the list:
diff = [X[i] - X[i-1] for i in range(1, len(X)) ]
There are more "Pythonic" ways to do this, but I want to make sure this is accessible to newer programmers.
You now have diff as
[1, 4, 1, 1, 3, 5]
Where you have a 1 in diff, you have a climbing pair in X. Iterate through diff to find a sequence of 1 values. Where you find this, take the slice of X that corresponds to the 1 values. The middle element of that slice is your mean.
If the value is not 1, then you simply take the corresponding element of X, as you've been doing.
append the identified values to z, and there's your desired result.
Can you take it from there?
Not really to answer the question, which is a fairly basic CS 101 question that people should try to figure out themselves, but what I noticed about the nice answer of #blhsing was that it appeared fairly slow. I found that mean() is incredibly slow!
from itertools import groupby, count
from statistics import mean
from timeit import timeit
def generate_1step_seq1(xs):
result = []
n = 0
while n < len(xs):
# sequences with step of 1 only
if not result or xs[n] == result[-1] + 1:
result += [xs[n]]
else:
# int result, rounding down
yield sum(result) // len(result)
result = [xs[n]]
n += 1
if result:
yield sum(result) // len(result)
def generate_1step_seq2(xs):
c = count()
return [int(sum(xs) // len(xs)) for xs in [list(g) for _, g in groupby(xs, key=lambda i: i - next(c))]]
def generate_1step_seq3(xs):
c = count()
return [int(mean(g)) for _, g in groupby(xs, key=lambda i: i - next(c))]
values = [0, 1, 5, 6, 7, 10, 15]
print(list(generate_1step_seq1(values)))
print(generate_1step_seq2(values))
print(generate_1step_seq3(values))
print(timeit(lambda: list(generate_1step_seq1(values)), number=10000))
print(timeit(lambda: list(generate_1step_seq2(values)), number=10000))
print(timeit(lambda: list(generate_1step_seq3(values)), number=10000))
Initially I figured that was probably due to the tiny list size, but even for large lists, mean() is horribly slow. Anyone happen to know why? It appears due to the very safe nature of statistics _sum, trying to avoid float rounding errors?

Slicing list the other way around?

I have this list:
arr = [1, 2, 3, 4, 5, 6]
What I wanted to do is make a new list with values from index 5 to index 1.
Output would be:
[6, 1, 2]
This is what I've done:
output = arr[5:] + arr[:2]
But I wanted to know if there's another way of slicing it.
Like just a normal slicing like for example:
output = arr[5:1]
But I know it's not gonna work because I've done that. Could you please help me?
As far as I'm aware, doing this without writing your own custom code doesn't seem possible. Python doesn't wrap lists around.
You can create a custom generator to do what you want, though:
>>> def cycle(l, start=0):
... l = l[start:] + l[:start]
... while True:
... x = l.pop(0)
... yield x
... l.append(x)
...
>>> k = cycle(a, 5)
>>> next(k)
6
>>> next(k)
1
>>> next(k)
2
(Example rolled back due to OP's post change.)
Here's an improved version that will take into account the number elements you want to get from the generator:
>>> def cycle(l, start=0, iters=None):
... l = l[start:] + l[:start]
... i = 0
... while True:
... if iters is not None and i == iters:
... raise StopIteration
... x = l.pop(0)
... yield x
... l.append(x)
... i += 1
...
>>> a = [1, 2, 3, 4, 5, 6]
>>> list(cycle(a, start=5, iters=3))
[6, 1, 2]
Update:
Rotate left n elements (or right for negative n) and slice number of element you want
L = L[n:] + L[:n] # rotate left n elements
In ur case n is 5:
>>> output = arr[5:] + arr[:5]
>>> output[:3]
[6, 1, 2]
Previous
>>> arr = [1, 2, 3, 4, 5, 6]
>>> output = arr[:]
>>> del output[2:5]
>>> output
[1, 2, 6]
>>>
Create a function to slice the input array for you and append the two parts together to get the desired list.
def cyc_slice(lst, start, n):
return lst[start:] + lst[:(start+n)%len(lst)]
Unlike both other answers, this doesn't make a superflous copy of all the list elements that you don't want.
>>> arr=[1,2,3,4,5,6]
>>> cyc_slice(arr, 5, 3)
[6, 1, 2]
And an improved iterator solution:
def cycle(l, start=0, n=None):
if not l:
return
idx = start-1
end = (idx + n) % len(l) if n else -1
while idx != end:
idx+=1
try:
x = l[idx]
except IndexError:
idx = 0
x = l[idx]
yield x
when provided with a count, it will provide that many elements. Otherwise, it can keep looping. This iterates through the list in place, so doesn't allocate any elements to memory (unless you create a list from it)
>>> list(cycle(arr,5,3))
[6, 1, 2]

Rotating values in a list [Python]

I understand this question has been asked before but I haven't seen any that answer it in a way without splitting the list.
say I have a list:
num = [1,2,3,4,5,6]
I want to create a function:
rotate(lst, x):
So that if I call rotate(num, 3) it will globally edit the list num. That way when I later call print(num) it will result in [4,5,6,1,2,3].
I understand that I could write the function something like:
rotate(lst, x):
return [lst[-x:] + lst[:-x]
But I need to do this function without a return statement, and without splitting the list. What I'm thinking would work would be to put the last value of the list into a variable: q = lst[-1] and then from there create a loop that runs x amount of times that continues to move the values towards the end of the list and replacing the 0th position with whatever is stored in q.
One more thing. If I call rotate(lst, -3) then instead of rotating to the "right" it would have to rotate to the "left".
I'm new to python and having trouble wrapping my mind around this concept of manipulating lists. Thank you everyone for your time and effort. I hope this problem was clear enough.
You can use slicing assignment to modify your current strategy to do what you want. You're already generating the rotated list correctly, just modify the list in place with lst[:] = ...
def rotate(lst, x):
lst[:] = lst[-x:] + lst[:-x]
Example in the interactive interpreter:
>>> l = [1, 2, 3, 4, 5, 6]
>>> def rotate(lst, x):
... lst[:] = lst[-x:] + lst[:-x]
...
>>> rotate(l, 2)
>>> l
[5, 6, 1, 2, 3, 4]
Now rotate it backwards:
>>> rotate(l, -2)
>>> l
[1, 2, 3, 4, 5, 6]
>>> rotate(l, -2)
>>> l
[3, 4, 5, 6, 1, 2]
See this answer on a different question: https://stackoverflow.com/a/10623383/3022310
Here is a solution using a double-ended queue.
As required, it modifies the list in place, neither uses return nor uses chunks of the list.
from collections import deque
def rotate(lst, x):
d = deque(lst)
d.rotate(x)
lst[:] = d
num = [1,2,3,4,5,6]
rotate(num,3)
print(num)
rotate(num,-3)
print(num)
produces
[4, 5, 6, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
Please have a look at PMOTW's tutorial on deque
def rotate(lst, num):
copy = list(lst)
for (i, val) in enumerate(lst):
lst[i] = copy[i - num]
Try:
num = [1,2,3,4,5,6]
def rotate(lst,x):
copy = list(lst)
for i in range(len(lst)):
if x<0:
lst[i+x] = copy[i]
else:
lst[i] = copy[i-x]
rotate(num, 2)
print num
Here is a simple method using pop and insert on the list.
num = [1,2,3,4,5,6]
def rotate(lst, x):
if x >= 0:
for i in range(x):
lastNum = lst.pop(-1)
lst.insert(0, lastNum)
else:
for i in range(abs(x)):
firstNum = lst.pop(0)
lst.append(firstNum)
return
print num #[1, 2, 3, 4, 5, 6]
rotate(num, 2)
print num #[5, 6, 1, 2, 3, 4]
rotate(num, -2)
print num #[1, 2, 3, 4, 5, 6]
I believe this satisfies all requirements. The idea is from the Programming Pearls book(http://goo.gl/48yJPw). To rotate a list we can reverse it and then reverse sublists with the rotating index as pivot.
def rotate(num, rot):
if rot < 0:
rot = len(num) + rot
rot = rot - 1
num.reverse()
for i in range(rot/2 + 1):
num[i], num[rot-i] = num[rot-i], num[i]
for i in range(1, (len(num) - rot)/2):
num[rot+ i], num[len(num) - i] = num[len(num) - i], num[rot+ i]
#Testing...
num = range(1, 10)
rot = -1
print num
rotate(num, rot)
print num

Categories

Resources