Python 中的滑动窗口

Vaibhhav Khetarpal 2022年5月18日
Python 中的滑动窗口

在任何给定点,可以说是给定特定数据结构的子集的任何窗口都称为滑动窗口。窗口大小决定了该子集将包含的元素数量。

本教程讨论滑动窗口并演示如何在 Python 中实现它。

使用滑动窗口的主要原因是它降低了时间复杂度。它专门以更快的速度解决使用蛮力方法解决的问题。

滑动窗口可用于简单的编码任务以及数字图像处理和对象检测等庞大而高级的任务。但是,本文将重点介绍一个简单的领域,以帮助你了解滑动窗口以及如何使用它。

为了更好地解释这一点,我们将举一个问题的例子,然后在其上实现一个滑动窗口。对于本文,我们采取以下问题:

给定一个大小为 x 的数字数组。找到具有最大总和的窗口大小 k 的子数组。

输入:x =[12,11,10,23,55,45,15,28],k=3。

现在,我们将应用一个滑动窗口来解决这个问题。

n = int(input("enter size of array "))
print("enter arrays elements")
a = list(map(int, input().split()))
k = int(input("enter the size of subarray "))
ms = -(10 ** 6)
ws = sum(a[:k])
for i in range(n - k):
    ms = max(ms, ws)
    ws = ws - a[i] + a[i + k]
ms = max(ms, ws)
print("subarray of size {} with maximum sum as {}".format(k, ms))

上面的代码提供了以下输出:

enter size of array 8
enter arrays elements
12 11 10 23 55 45 15 28
enter the size of subarray 3
subarray of size 3 with maximum sum as 123
Vaibhhav Khetarpal avatar Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

LinkedIn

相关文章 - Python Array