-1

Consider the following:

Let's say we have an array of integers of an arbitrary length L.

[a,b,c,...,z]

I know we can easily split this array and create multiple arrays of length n: [a,b], [c,d],..., [y,z]

How would we split this array and return something such as [a,b,c], [b,c,d], [c,d,e], ..., [w,x,y], [x,y,z]?

Essentially, if given an array can we create new arrays from that array using any function of our choosing? Does the type of function affect how we do this? How fancy can we get?

Most of what I've found involves slicing an array first and then performing operations on the new arrays. I'd like to create my arrays based on a function of my choosing.

TheArtofXin
  • 33
  • 1
  • 4
  • 1
    Using "map" with the value or index to create a new array of arrays. That way you can create a function as you want. – Myrtue Oct 08 '18 at 19:08
  • https://stackoverflow.com/questions/6822725/rolling-or-sliding-window-iterator – mad_ Oct 08 '18 at 19:28
  • _"I'd like to slice my arrays based on a function of my choosing."_ What does this mean? Can you provide an example code that shows how you imagine it working? – AGN Gazer Oct 08 '18 at 19:52

1 Answers1

0

Just using the index to slice the array and moving the window by one step. Break when the size of window is less than expected

a=[1,2,3,4,5,6,7,8,9]
def slicing_window(a,n):
    new_arr=[]
    if(len(a)<n):
        return a
    for i in range(0,len(a)):
        if len(a[i:i+n])==n:
            new_arr.append(a[i:i+n])
        else:
            break
    return new_arr
slicing_window(a,3) 

Output:

[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]

OR

from toolz import sliding_window
list(sliding_window(3, a))# will generate tuples

If you are interested in just list

from toolz import sliding_window
map(list,sliding_window(3, a))
mad_
  • 8,121
  • 2
  • 25
  • 40