Skip to content

Instantly share code, notes, and snippets.

@RahulDas-dev
Created August 8, 2022 08:29
Show Gist options
  • Save RahulDas-dev/8d0ae23b6715026e4d7123e402d77f2c to your computer and use it in GitHub Desktop.
Save RahulDas-dev/8d0ae23b6715026e4d7123e402d77f2c to your computer and use it in GitHub Desktop.
1D Sliding Window
import math
from typing import List
def sliding_window(input_: List[int], kernel_: List[int]) -> List[int]:
# Checking input and kernel length constraint
if len(kernel_) > len(input_):
raise ValueError("Input Size must be gratter than Kernel size")
start_index = 0
end_index = len(kernel_)
# Calculating output array size
quo,mod = divmod(len(input_), len(kernel_))
output_size = quo if mod == 0 else quo+1
# Initializing output array
output = []
for i in range(output_size):
# Convolution Calculation
input_segment = input_[start_index:end_index]
convolution = [ a*b for a, b in zip(input_segment, kernel_)]
output.append(convolution)
# Moving start_index and end_index
start_index = end_index
end_index = start_index + len(kernel_)
if start_index > end_index:
break
return output
output= sliding_window([1,2,3,4,5,6,7,8,9,0,11,12,1,3,14,15],[1,0,1])
print(output)
@RahulDas-dev
Copy link
Author

sliding_window

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment