Mike5298
Mike5298

Reputation: 385

How to rotate an array in Python?

I'm trying to rotate an array in Python. I've read the following post Python Array Rotation

Where I found this little snippet of code

arr = arr[numOfRotations:]+arr[:numOfRotations]

I've tried to put this into the following function:

def solution(A, K):
    A = A[K:] + A[:K]
    print(A)
    return A

Where A is my array and K is the number of rotations. Only I get the following error, ValueError: operands could not be broadcast together with shapes (3,) (2,).

I don't understand where I'm going wrong? Ideally I a solution that can solve this without using any Numpy inbuilt short cuts functions.

Cheers

Edit: This is the full program

A = np.array([1, 2, 3, 4, 5])

def solution(A, K):
    A = A[K:]+A[:K]
    print(A)
    return A

solution(A, 2)

Upvotes: 4

Views: 1883

Answers (1)

Ajay Verma
Ajay Verma

Reputation: 630

You need to use np.concatenate((A[K:],A[:K])) if A is an array, you function works when A is list

Lest try to look at from your example

A = np.array([1, 2, 3, 4, 5])
K = 2
print(A[K:])
print(A[:K])

Will give you [3 4 5] and [1 2] . in your code you are trying to add them using + sign. Since the these two values are of different shapes you cant add them, hence you will get ValueError: operands could not be broadcast together with shapes (3,) (2,)

The correct implementation for an array will be

import numpy as np
A = np.array([1, 2, 3, 4, 5])

def solution(A, K):
    A = np.concatenate((A[K:],A[:K]))
    print(A)
    return A

Upvotes: 2

Related Questions