Created
January 26, 2023 03:29
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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