Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how cyclic fetch a pre-fixed number of elements in array

I'm trying to make a function that will always return me a pre-fixed number of elements from an array which will be larger than the pre-fixed number:

def getElements(i,arr,size=10):
    return cyclic array return

where i stands for index of array to fetch and arr represent the array of all elements:

Example:

a = [0,1,2,3,4,5,6,7,8,9,10,11]
b = getElements(9,a)
>> b
>> [9,10,11,0,1,2,3,4,5,6]
b = getElements(1,a)
>> b
>> [1,2,3,4,5,6,7,8,9,10]

where i = 9 and the array return the [9:11]+[0:7] to complete 10 elements with i = 1 don't need to cyclic the array just get [1:11]

thanks for the help

Initial code (not working):

def getElements(i,arr,size=10):
    total = len(arr)
    start = i%total
    end = start+size
    return arr[start:end]

#not working cos not being cyclic

EDIT:

I can't make any import for this script

like image 840
Alvaro Joao Avatar asked Sep 16 '16 05:09

Alvaro Joao


2 Answers

You could return

array[i: i + size] + array[: max(0, i + size - len(array))]

For example

In [144]: array = list(range(10))

In [145]: array
Out[145]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [146]: i, size = 1, 10

In [147]: array[i: i + size] + array[: max(0, i + size - len(array))]
Out[147]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

In [148]: i, size = 2, 3

In [149]: array[i: i + size] + array[: max(0, i + size - len(array))]
Out[149]: [2, 3, 4]

In [150]: i, size = 5, 9

In [151]: array[i: i + size] + array[: max(0, i + size - len(array))]
Out[151]: [5, 6, 7, 8, 9, 0, 1, 2, 3]
like image 117
Ami Tavory Avatar answered Oct 20 '22 01:10

Ami Tavory


The itertools is a fantastic library with lots of cool things. For this case we can use cycle and islice.

from itertools import cycle, islice
def getElements(i, a, size=10):
    c = cycle(a) # make a cycle out of the array
    list(islice(c,i)) # skip the first `i` elements
    return list(islice(c, size)) # get `size` elements from the cycle

Works just as you wanted.

>>> getElements(9, [0,1,2,3,4,5,6,7,8,9,10,11])
[9, 10, 11, 0, 1, 2, 3, 4, 5, 6]
like image 44
Sevanteri Avatar answered Oct 19 '22 23:10

Sevanteri