diff --git a/_black_version.py b/_black_version.py new file mode 100644 index 000000000000..86b89cb8833d --- /dev/null +++ b/_black_version.py @@ -0,0 +1 @@ +version = "23.3.0" diff --git a/dynamic_programming/max_sub_array_sum.py b/dynamic_programming/max_sub_array_sum.py new file mode 100644 index 000000000000..be1a42152684 --- /dev/null +++ b/dynamic_programming/max_sub_array_sum.py @@ -0,0 +1,43 @@ +def max_sub_array_sum(arr: list[int], size: int) -> int: + """ + Finds the maximum sum of a subarray within the given array using Kadane's algorithm. + + Args: + arr (list): The input array of numbers. + size (int): The size of the array. + + Returns: + int: The maximum sum of a subarray within the array. + + Example: + >>> arr = [-2, -3, 4, -1, -2, 5, -3] + >>> max_sub_array_sum(arr, len(arr)) + 6 + In this example, the input array is [-2, -3, 4, -1, -2, 5, -3]. + The maximum sum of a subarray within this array is 6, + which corresponds to the subarray [4, -1, -2, 5]. + + >>> arr = [-3, -4, 5, -1, 2, -4, 6, -1] + >>> max_sub_array_sum(arr, len(arr)) + 8 + + References: + https://en.wikipedia.org/wiki/Maximum_subarray_problem + """ + max_till_now = arr[0] + max_ending = 0 + + for i in range(size): + max_ending = max_ending + arr[i] + if max_ending < 0: + max_ending = 0 + elif max_till_now < max_ending: + max_till_now = max_ending + + return max_till_now + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/web_programming/sliding_window.py b/web_programming/sliding_window.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/web_programming/sliding_window_generators.py b/web_programming/sliding_window_generators.py new file mode 100644 index 000000000000..217396236db5 --- /dev/null +++ b/web_programming/sliding_window_generators.py @@ -0,0 +1,37 @@ +from collections.abc import Generator + + +def sliding_window( + elements: list[int], window_size: int +) -> Generator[list[int], None, None]: + """ + Generate sliding windows of size window_size from the given elements. + + Args: + elements (list): The input list of elements. + window_size (int): The size of the sliding window. + + Returns: + generator: A generator that yields sublists of size window_size. + + Example: + >>> lst = [1, 2, 3, 4, 5, 6, 7, 8] + >>> sw_gen = sliding_window(lst, 3) + >>> print(next(sw_gen)) + [1, 2, 3] + >>> print(next(sw_gen)) + [2, 3, 4] + + References: + https://stackoverflow.com/questions/8269916/what-is-sliding-window-algorithm-examples + """ + if len(elements) <= window_size: + yield elements + for i in range(len(elements) - window_size + 1): + yield elements[i : i + window_size] + + +if __name__ == "__main__": + import doctest + + doctest.testmod()