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)
3
  • 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) Commented Oct 2, 2020 at 8:10
  • 1
    Really these don't work??? Worked for me with solution([1,2,3],1) in test Commented Oct 2, 2020 at 8: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 Commented Oct 2, 2020 at 8:28

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.