Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Created January 26, 2023 03:29
Show Gist options
  • Save ianfoo/432de1cca01a6385bfadf129e45c5a3e to your computer and use it in GitHub Desktop.
Save ianfoo/432de1cca01a6385bfadf129e45c5a3e to your computer and use it in GitHub Desktop.
Calculate the product of a sliding window of integers in a list (Python)
from functools import reduce
def window_product(input: list[int], current_pos: int, window_size: int) -> int:
window_bound = max(current_pos + 1 - window_size, 0)
window = input[window_bound : current_pos + 1]
product = reduce(lambda a, b: a*b, window)
return product
def window_products(input: list[int], window_size: int) -> list[int]:
products = [window_product(input, n, window_size) for n in range(len(input))]
return products
def main():
input = [2, 7, 8, 1, 9, 5]
WINDOW_SIZE = 3
print(window_products(input, WINDOW_SIZE))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment