Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
rotating an array
#1
I'm trying to write a code to rotate an array by a given value. Here's my code:

A = [4,6,8,9,1]
K = 2

def rotate_array(A,K):
    for x in A:
        y = x + K
        if y >= len(A):
            y = y - len(A)
        A[x] = A[y]
        
    print(A)

rotate_array(A,K)
I'm getting this error:
Error:
File "c:\Users\djwil\Documents\python\codility\cyclic_array.py", line 14, in <module> rotate_array(A,K) File "c:\Users\djwil\Documents\python\codility\cyclic_array.py", line 10, in rotate_array A[y] = A[x] IndexError: list index out of range
However I'm not sure why I'm getting this error as I wrote the lines below to stop this error from occuring:

if y >= len(A):
      y = y - len(A)
Can someone help me with this please?
Reply
#2
(Jan-07-2021, 05:01 PM)djwilson0495 Wrote: I'm trying to write a code to rotate an array by a given value.

It's already implemented. Have a look at collections.deque
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
It will be easier to see your error if you changed the "array" from a list of numbers to a list of number strings.
A = ['4','6','8','9','1']
K = 2
 
def rotate_array(A,K):
    for x in A:
        y = x + K
        if y >= len(A):
            y = y - len(A)
        A[x] = A[y]
         
    print(A)
 
rotate_array(A,K)
Output:
Traceback (most recent call last): File "...", line 13, in <module> rotate_array(A,K) File "...", line 6, in rotate_array y = x + K TypeError: can only concatenate str (not "int") to str
"for x in A" does not set "x" to 0, 1, 2, 3, 4, 5, it sets "x" to values pulled from "A". In my example the first iteration has x = '4' and then I try to add '4' + 2 and that is an error. In your example the first iteration is x = 4. Python can add 4 + 2 to get y = 6, but this is not the correct value for rotating your array. You want y = 2, so A[0] = A[2]. The exception occurs when x = 8 because 8 + K - len(A) = 5, and A[5] is not a valid index.

You probably wanted to do something like this:
def rotate_array(A,K):
    size = len(A)
    for i in range(size):
        A[i] = A[(i + K) % size]
    return A
 
A = ['4','6','8','9','1']
print(rotate_array(A,2))
Output:
['8', '9', '1', '8', '9']
But as you can see the output is incorrect. Things start out well with 8, 9, 1, but when you wrap around past the end of A[] you start using list elements that have already been modified. A[0] is now '8' instead of '4' and A[1] is '9' instead of '6', so the last two elements in the result are copies of the first two elements of the result, not of the initial list.

This problem is easily fixed by making a new list instead of trying to modify the original list.
def rotate_array(A,K):
    size = len(A)
    return [A[(i + K) % size] for i in range(size)] # list comprehension
 
A = ['4','6','8','9','1']
print(rotate_array(A,2))
Output:
['8', '9', '1', '4', '6']
Or using slices.
def rotate_array(A,K):
    return A[K:] + A[:K]
 
A = ['4','6','8','9','1']
print(rotate_array(A,2))
Output:
['8', '9', '1', '4', '6']
You can even use slices to rotate the contents in A instead of creating a new list.
def rotate_array(A,K):
    A[:] = A[K:] + A[:K]
 
A = ['4','6','8','9','1']
rotate_array(A,2)
print(A)
Output:
['8', '9', '1', '4', '6']
And just to fill out the list of how to solve this problem, here's a solution that uses queue like (or dequeue like) features that are available for lists.
def rotate_array(A,K):
    for _ in range(K):
        A.append(A.pop(0))
 
A = ['4','6','8','9','1']
rotate_array(A,2)
print(A)
Output:
['8', '9', '1', '4', '6']
Skaperen likes this post
Reply
#4
or, just to be thoroughly complete, a single slice of a concatenation of the array with itself:

def rotate_array(A,K):
    A[:] = (A+A)[K:K+len(A)]

A = ['4','6','8','9','1']
rotate_array(A,2)
print(A)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  rotating image with Tkinter Frankduc 6 6,597 May-21-2022, 03:00 PM
Last Post: Frankduc
  rotating and resizing objects jenya56 3 2,380 Jul-26-2019, 12:06 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020