1

so I have this list,

List: [0, 0, 1, 0, 1];

And I need made a algorithm with a for to show all the list (list[i]).

When I am in first array position, I can do list[i-2] and list[i-1], with this I can see the elements of the last position and the position before the last position.

Exemple : list[0] = 0; list[i-1] = list[4] = 1; list[i-2] = list[3] = 0; so I can go to the last position and start from there.

But when I do, list[i+1] in the last position I got a IndexError: list index out of range from the terminal.

My question is: If I was in the last positions and I want again come to from the first one and keep doing the for loop, to see infinite times all array elements from all positions, How I can do it? If the size of my array it is 5, and I am in second position(list[1]) in the loop and want do list[i + 11], how can I put this representing this, list[2]?

I am trying make this on python.

Miguel Soeiro
  • 129
  • 1
  • 8

3 Answers3

1

You can achieve this using the modulo operator, which returns the remainder of the division of its two operands. In this case, you would do the following: list[i%num_of_elements], where num_of_elements is a variable holding the number of elements in the list.

1

I believe your asking about rotating arrays, if this isn't what you meant, just comment.

def rotateLeft(li):
    return li[1:] + [li[0]]

def rotateRight(li):
    return [li[len(li)-1]] + li[:len(li)-1]

li = [1,2,3,4,5]

print (rotateLeft(li))
print (rotateRight(li))
Neil
  • 14,063
  • 3
  • 30
  • 51
  • `rotateRight(li)` can be simplified like `return [li[-1]] + li[:-1]` – Johan Aug 31 '18 at 20:44
  • Or, perhaps more efficient version of `rotateLeft()` would be `li.append(li.pop(0))` (though I don't know how it works internally in python). – Johan Aug 31 '18 at 20:47
0

You can implement such an "infinite iterator" as follows:

def infinite_iterator(lst):    
    i = 0
    def next():        
        global i
        while True:
            result = lst[i % len(lst)]
            i += 1
            yield result
    return next()

and use it with:

lst = [1,2,3,4,5]    
iter = infinite_iterator(lst)

for i in range(17): # 17 is just an example, you can put any number or `while True:` 
    print(next(iter))
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129