Home > OS >  Facing an IndexError for rotating a list
Facing an IndexError for rotating a list

Time:12-04

I have just started programming and started solving problems. During my practice, I came across this problem and cannot understand why my code is not working. So the task is to cyclically rotate the array consisting of N elements, clockwise by K.

Example 1: 5 —Value of N

{10, 20, 30, 40, 50} —Element of Arr[ ]

2 —–Value of K

Output : 40 50 10 20 30

I attempted to solve it by this Python 3 code:

Arr=[]
Arr2=[]
N=int(input("Enter the number of elements:"))
k=int(input())
if (k>N):
  k=k%N

for i in range (0,N):
  a=input()
  Arr.append(a)

for i in range (0,N):
  if ((i k)<N):
    Arr2[i k]=Arr[I]
else:
    Arr2[i k-N]=Arr[I]
print (Arr2)

It is showing an IndexError for arr2[i k] even though it should never go to that index as there is the condition (i k<N). Please can someone explain it to me? Thanks

CodePudding user response:

Well you have to first define Arr2 as a list with a fixed size. Something like this:

Arr2 = [0]*N

which gives you an output of Arr2 to be:

[0, 0, 0, 0, 0]

Then, it is safe to include your final snippet of code:

for i in range (0,N):
  if ((i k)<N):
    Arr2[i k]=Arr[i]
else:
    Arr2[i k-N]=Arr[i]
print (Arr2)

CodePudding user response:

Actually Arr2 has no any elements. So you cannot assign a value to if there nothing at the given index.

Arr2[i k]=Arr[I]

Here have to define i k index in the Arr2.

If it is works for you you try this one but this is temporary solution not the perfect way.

Arr2 = []

for i in range(1000):
  Arr2.append(0)

print(len(a))

you can change inside of range function. I can't get your mathematically representation about that but you can change that part with your maximum index formula of your problem.

  • Related