2

I want to generate contiguous sliding window from a list

nums = [1,2,3,4,10]

####O/P 
[[1, 2], [2, 3], [3, 4], [4, 10]]

My code so far -

>>> num_list = [1,2,3,4,10]
>>> 
>>> res = []
>>> n = len(num_list)
>>> 
>>> for i in range(n):
...     imm = []
...     for j in range(i,i+1):
...             imm += [num_list[i], num_list[j]]
...     res += [imm]
... 
>>> res
[[1, 1], [2, 2], [3, 3], [4, 4], [10, 10]]

I m beginner in python , the num_list is a just fraction of the actual list, its longer

3 Answers3

4

You can use zip to create a list of consecutive pairs from the list by passing the original list and a slice of the list offset by 1:

list(zip(num_list, num_list[1:]))
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
2

What you are trying to achieve is a sliding window

You can try the below function , it also reduces your Time Complexity from O(N^2) to O(N)

Other resources

l = [1,2,3,4,10]

def divide_chunks_contigious(in_arr,chunk):
    n = len(in_arr)
    i = 0
    while i + chunk <= n:
        i += 1
        yield in_arr[i-1:i+chunk-1]

>>> list(divide_chunks_contigious(l,2))
[[1, 2], [2, 3], [3, 4], [4, 10]]

Also the problem with your code can be resolved by initilizing j from i+1 till i+2 , but over long sequences it would be slower

for i in range(n-1):
    imm = []
    for j in range(i+1,i+2):
        imm += [num_list[i],num_list[j]]
    res += [imm]

>>> res
[[1, 2], [2, 3], [3, 4], [4, 10]]
Vaebhav
  • 4,672
  • 1
  • 13
  • 33
  • The time complexity of the code in question is also O(N) as the second for loop will iterate only once so, O(N*1) isn't it? – Aakash aggarwal Jan 31 '21 at 07:59
  • This is valid when chunk size is 2 (adjacent element) , What happens when the chunk size is greater than 2 , the second loop will become longer – Vaebhav Jan 31 '21 at 08:05
  • if the chunk size increases then yes, But here chunk size is hardcoded to 1 though So, the time complexity is O(N) right? – Aakash aggarwal Jan 31 '21 at 08:09
0

In your code in second for loop

for  j in range(i, i+1):
    print(j)
# j = i

that's why your result is not right you can use this below code

n = [1,2,3,4,5]
ans = []
for i in range(len(n)-1):
    ans.append([n[i], n[i+1]])
print(ans)
# ans = [[1,2], [2,3],[3,4],[4,5]]
Dharman
  • 30,962
  • 25
  • 85
  • 135
Aakash aggarwal
  • 443
  • 2
  • 6
  • 21