Home > Enterprise >  How to iterate through a circular array multiple times in python?
How to iterate through a circular array multiple times in python?

Time:01-21

I want to circle through the array multiple times. When I reach the last index, the next index should be the first one. For example, I have an array of 6 elements

array1 = [1,2,3,4,5,6]

and I have K = 4. K will be the number of elements that I will skip.

In the above example, I will start from array1[0] and skip K elements including the array1[0] element. So if I skip 4 elements, I will reach array1[4]. If I skip K elements once more, I should skip array1[4], array1[5], array1[0] and array1[1] and reach array1[2]. This process will repeat itself N times.

I tried searching for the solution online because I cannot think of a way to move through the array in circle. I found one solution that says to use modulo operator like this

print a[3 % len(a)] 

but I cannot understand this since I am just starting out with python.

CodePudding user response:

Understanding what modulo is will be helpful https://en.wikipedia.org/wiki/Modulo

To sum up, in this exercise you don't care how many times you went through the array. You only care about "at which position of the current iteration you are" lets say. Therefore, a modulo operation using the length of the array as modulo will give you the remainder of such division, which is exactly what you are looking for.

Example:

arr = [1,2,3,4,5]
k = 27
arrlength = len(arr) # 5
reminder = k % arrlength # 27 % 5 = 2
arr[reminder] # 3

CodePudding user response:

So, the modulo operator returns the remainder from the division between two numbers.

Example:

6 % 2 = 0 # because 6/2 = 3 with no remainder
6 % 5 = 1 # because 6/5 = 1 (integer part) plus remainder 1
6 % 7 = 6 # because 7 doesn't fit in 6, so all the dividend goes into the remainder

So your problem can be solved by something like this:

arr = [1,2,3,4,5,6]
N = 5
step = 4

for i in range(5):
    print(arr[(i 1)*step%len(arr)])

where N is the number of elements you want to print

This is the same as creating an extended list such as:

b = arr * 1000

and print each element in range(step,(N 1)*step,step). Of course this method is not optimal since you don't now how many arrays arr you have to concatenate in order not to go out of bounds.

Hope it helped

  • Related