Johni Douglas Marangon
Johni Douglas Marangon

Reputation: 587

Array index start random in Python

I need to visit items in array starting to index random.

My code

from random import randrange

fruits = ['banana', 'apple',  'mango']

index = randrange(len(fruits))
for index in fruits[index:]:
     print index

It is possible when index is 1 or 2 after to print start again in index 0 or 1 in that loop for.

Example:

Randon index is 1 print = 'apple' 'mango' 'banana'

Randon index is 2 print = 'mango' 'apple' 'banana'

Upvotes: 1

Views: 223

Answers (4)

Harpal
Harpal

Reputation: 12587

You could avoid a for loop and splice up to the index then reverse the elements greater than the index

>>> fruits = ['banana', 'apple',  'mango']
>>> index = 0
>>> fruits[index:] + fruits[:index][::-1]
['banana', 'apple', 'mango']
>>> index = 1
>>> fruits[index:] + fruits[:index][::-1]
['apple', 'mango', 'banana']
>>> index = 2
>>> fruits[index:] + fruits[:index][::-1]
['mango', 'apple', 'banana']

Upvotes: 1

nneonneo
nneonneo

Reputation: 179442

It looks like you're just trying to visit the list in random order (since your two sample outputs aren't both rotations of the original list).

In that case, may I suggest random.shuffle?

import random
randlist = fruits[:]
random.shuffle(randlist)
for i in randlist:
    print i

This prints the list in a random order.

Upvotes: 2

nmclean
nmclean

Reputation: 7734

A deque is built for this operation: collections.deque

Instead of using fruits[index:], you could create a deque and rotate it:

from collections import deque

fruit_deque = deque(fruits)
fruit_deque.rotate(-index)

for fruit in fruit_deque:
    print fruit

Another option is cycle and islice:

from itertools import cycle, islice

fruit_cycle = cycle(fruits)
fruit_slice = islice(fruit_cycle, index, index + len(fruits))

for fruit in fruit_slice:
    print fruit

You could wrap around more than once with this method, by replacing len(fruits) with any number (or use islice(fruit_cycle, index, None) to cycle indefinitely).

Upvotes: 2

will
will

Reputation: 10650

Try this

from random import randrange

fruits = ['banana', 'apple',  'mango']
randomOffset = randrange(0,len(fruits))
for i in range(len(fruits)):       
   print fruits[i - randomOffset]

You could use an index of (i + randomOffset) % len(fruits) to be more clear, but giving a negative index in python works by starting from the back of the array and counting backwards. So in effect, you'd be just starting somewhere randomly in the array - set by randomOffset, and then takign al lthe subsequent items.

Upvotes: 2

Related Questions