4

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)
Mike5298
  • 377
  • 1
  • 13
  • 1
    Could you show us how you are calling your method ? The code you provided work well for me using `solution([1,2,3], 1)` – gcourtet Oct 02 '20 at 08:10
  • 1
    Really these don't work??? Worked for me with `solution([1,2,3],1)` in test – Wasif Oct 02 '20 at 08:10
  • So when I call it the same way you two did it works fine, but this method provides a list as the argument and not an array. Which seems to be the issue – Mike5298 Oct 02 '20 at 08:28

1 Answers1

2

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
Ajay Verma
  • 610
  • 2
  • 12