Home > Net >  My for loop is not iterating correctly in array rotation problem in Python
My for loop is not iterating correctly in array rotation problem in Python

Time:07-17

I'm trying to write a solution to Codility problem 2.1 in Python. The taks is to write a function to rotate a given array one space to the right k number of times. For example, if you were to rotate [0, 1, 2, 3, 4] twice it would first become [4, 0, 1, 2, 3] and then [3, 4, 0, 1, 2].

I'm doing this by writing two for loops, the inner for loop to rotate the array and the outer for loop to repeat the rotation k times. I haven't moved on to write the outer loop yet but I think it should be straightforward. However, I'm struggling to write the inner loop to rotate the array.

When I test [0, 1, 2, 3, 4] it returns [4, 1, 2, 3, 3] instead of [4, 0, 1, 2, 3], so it only returns the first and last elements correctly. The loop doesn't seem to cycle through the second, third and fourth elements at all (I have tested this by asking the loop to print(i) when it cycles through the loop).

Can anyone see why my for loop isn't working? The code is below

def Solution(A):
    N = len(A)
    A_minus_one_original = A[-1]
    for i in (-1, -N):
        if i != -N:
            A[i] = A[int(i) - 1]
            print(i)
        elif i == -N: 
            A[i] = A_minus_one_original
            print(i)
    print(A)

CodePudding user response:

for i in range(-1, -N, -1)

Use this for loop, because yours only touch the -1 and -N positions

BTW, python supports array slicing, which is very useful for rotate the array k steps (k < len(a)).

# left
new_a = a[k:]   a[:k]      
# right
la = len(a)
new_a = a[la-k:]   a[:la-k]

CodePudding user response:

Don't forget to name your variables to make your code readable. I solved the problem in that way. 

def solution(list_to_rotate,rotation_time):
    last_index_list_to_rotate = -1
    rotation_time = rotation_time - 1
    for i in range(last_index_list_to_rotate, rotation_time):
        if i != rotation_time:
            val = list_to_rotate[last_index_list_to_rotate]
            del list_to_rotate[last_index_list_to_rotate]
            list_to_rotate.insert(0,val)
            print(i)
    print(list_to_rotate)

#rotate twice the list
solution([0,1,2,3,4],2)
``
  • Related