Reputation: 949
I want to find connected (adjacent) elements in array.
For example, in the array:
[1,2,3,4,5]
To access all 2-connected elements, output would be:
1,2
2,3
3,4
4,5
To access all 3-connected elements, output would be
1,2,3
2,3,4
3,4,5
So as input I have an array and a value of n adjacent elements, and need to generate all the cases
With basic for loop:
for x in xrange(n):
I can get all the values of the index of the array, but I'm not sure how to get the next elements (using while loop runs into problem because the last index will not have any adjacent elements)
(What I was thinking of)
array = [1,2,3,4,5]
answer = []
for x in xrange(n):
while len(answer) < adjacent_value:
answer.append(array[x])
x+=1
Upvotes: 1
Views: 879
Reputation: 239443
def grouper(input_list, n):
return [input_list[i:i + n] for i in range(len(input_list) + 1 - n)]
print grouper([1, 2, 3, 4, 5], 3)
# [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
print grouper([1, 2, 3, 4, 5], 2)
# [[1, 2], [2, 3], [3, 4], [4, 5]]
Upvotes: 3