Skip to content

Fix sphinx/build_docs warnings for dynamic_programming #12484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions dynamic_programming/all_construct.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,10 @@

def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]:
"""
returns the list containing all the possible
combinations a string(target) can be constructed from
the given list of substrings(word_bank)
returns the list containing all the possible
combinations a string(`target`) can be constructed from
the given list of substrings(`word_bank`)
>>> all_construct("hello", ["he", "l", "o"])
[['he', 'l', 'l', 'o']]
>>> all_construct("purple",["purp","p","ur","le","purpl"])
Expand Down
23 changes: 12 additions & 11 deletions dynamic_programming/combination_sum_iv.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
"""
Question:
You are given an array of distinct integers and you have to tell how many
different ways of selecting the elements from the array are there such that
the sum of chosen elements is equal to the target number tar.
You are given an array of distinct integers and you have to tell how many
different ways of selecting the elements from the array are there such that
the sum of chosen elements is equal to the target number tar.
Example
Input:
N = 3
target = 5
array = [1, 2, 5]
* N = 3
* target = 5
* array = [1, 2, 5]
Output:
9
9
Approach:
The basic idea is to go over recursively to find the way such that the sum
of chosen elements is “tar”. For every element, we have two choices
1. Include the element in our set of chosen elements.
2. Don't include the element in our set of chosen elements.
The basic idea is to go over recursively to find the way such that the sum
of chosen elements is `target`. For every element, we have two choices
1. Include the element in our set of chosen elements.
2. Don't include the element in our set of chosen elements.
"""


Expand Down
11 changes: 6 additions & 5 deletions dynamic_programming/fizz_buzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@

def fizz_buzz(number: int, iterations: int) -> str:
"""
Plays FizzBuzz.
Prints Fizz if number is a multiple of 3.
Prints Buzz if its a multiple of 5.
Prints FizzBuzz if its a multiple of both 3 and 5 or 15.
Else Prints The Number Itself.
| Plays FizzBuzz.
| Prints Fizz if number is a multiple of ``3``.
| Prints Buzz if its a multiple of ``5``.
| Prints FizzBuzz if its a multiple of both ``3`` and ``5`` or ``15``.
| Else Prints The Number Itself.
>>> fizz_buzz(1,7)
'1 2 Fizz 4 Buzz Fizz 7 '
>>> fizz_buzz(1,0)
Expand Down
40 changes: 21 additions & 19 deletions dynamic_programming/knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def mf_knapsack(i, wt, val, j):
"""
This code involves the concept of memory functions. Here we solve the subproblems
which are needed unlike the below example
F is a 2D array with -1s filled up
F is a 2D array with ``-1`` s filled up
"""
global f # a global dp table for knapsack
if f[i][j] < 0:
Expand Down Expand Up @@ -45,22 +45,24 @@ def knapsack_with_example_solution(w: int, wt: list, val: list):
the several possible optimal subsets.
Parameters
---------
----------
W: int, the total maximum weight for the given knapsack problem.
wt: list, the vector of weights for all items where wt[i] is the weight
of the i-th item.
val: list, the vector of values for all items where val[i] is the value
of the i-th item
* `w`: int, the total maximum weight for the given knapsack problem.
* `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight
of the ``i``-th item.
* `val`: list, the vector of values for all items where ``val[i]`` is the value
of the ``i``-th item
Returns
-------
optimal_val: float, the optimal value for the given knapsack problem
example_optional_set: set, the indices of one of the optimal subsets
which gave rise to the optimal value.
* `optimal_val`: float, the optimal value for the given knapsack problem
* `example_optional_set`: set, the indices of one of the optimal subsets
which gave rise to the optimal value.
Examples
-------
--------
>>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
(142, {2, 3, 4})
>>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
Expand Down Expand Up @@ -104,19 +106,19 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
a filled DP table and the vector of weights
Parameters
---------
dp: list of list, the table of a solved integer weight dynamic programming problem
----------
wt: list or tuple, the vector of weights of the items
i: int, the index of the item under consideration
j: int, the current possible maximum weight
optimal_set: set, the optimal subset so far. This gets modified by the function.
* `dp`: list of list, the table of a solved integer weight dynamic programming
problem
* `wt`: list or tuple, the vector of weights of the items
* `i`: int, the index of the item under consideration
* `j`: int, the current possible maximum weight
* `optimal_set`: set, the optimal subset so far. This gets modified by the function.
Returns
-------
None
``None``
"""
# for the current item i at a maximum weight j to be part of an optimal subset,
# the optimal value at (i, j) must be greater than the optimal value at (i-1, j).
Expand Down
14 changes: 9 additions & 5 deletions dynamic_programming/longest_common_substring.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
"""
Longest Common Substring Problem Statement: Given two sequences, find the
longest common substring present in both of them. A substring is
necessarily continuous.
Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de".
Therefore, algorithm should return any one of them.
Longest Common Substring Problem Statement:
Given two sequences, find the
longest common substring present in both of them. A substring is
necessarily continuous.
Example:
``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``.
Therefore, algorithm should return any one of them.
"""


def longest_common_substring(text1: str, text2: str) -> str:
"""
Finds the longest common substring between two strings.
>>> longest_common_substring("", "")
''
>>> longest_common_substring("a","")
Expand Down
13 changes: 8 additions & 5 deletions dynamic_programming/longest_increasing_subsequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
This is a pure Python implementation of Dynamic Programming solution to the longest
increasing subsequence of a given sequence.

The problem is :
Given an array, to find the longest and increasing sub-array in that given array and
return it.
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return
[10, 22, 33, 41, 60, 80] as output
The problem is:
Given an array, to find the longest and increasing sub-array in that given array and
return it.

Example:
``[10, 22, 9, 33, 21, 50, 41, 60, 80]`` as input will return
``[10, 22, 33, 41, 60, 80]`` as output
"""

from __future__ import annotations
Expand All @@ -17,6 +19,7 @@
def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive
"""
Some examples

>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
[10, 22, 33, 41, 60, 80]
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])
Expand Down
89 changes: 48 additions & 41 deletions dynamic_programming/matrix_chain_multiplication.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,48 @@
"""
Find the minimum number of multiplications needed to multiply chain of matrices.
Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
| Find the minimum number of multiplications needed to multiply chain of matrices.
| Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/

The algorithm has interesting real-world applications. Example:
1. Image transformations in Computer Graphics as images are composed of matrix.
2. Solve complex polynomial equations in the field of algebra using least processing
power.
3. Calculate overall impact of macroeconomic decisions as economic equations involve a
number of variables.
4. Self-driving car navigation can be made more accurate as matrix multiplication can
accurately determine position and orientation of obstacles in short time.
The algorithm has interesting real-world applications.

Python doctests can be run with the following command:
python -m doctest -v matrix_chain_multiply.py
Example:
1. Image transformations in Computer Graphics as images are composed of matrix.
2. Solve complex polynomial equations in the field of algebra using least processing
power.
3. Calculate overall impact of macroeconomic decisions as economic equations involve a
number of variables.
4. Self-driving car navigation can be made more accurate as matrix multiplication can
accurately determine position and orientation of obstacles in short time.

Given a sequence arr[] that represents chain of 2D matrices such that the dimension of
the ith matrix is arr[i-1]*arr[i].
So suppose arr = [40, 20, 30, 10, 30] means we have 4 matrices of dimensions
40*20, 20*30, 30*10 and 10*30.
Python doctests can be run with the following command::

matrix_chain_multiply() returns an integer denoting minimum number of multiplications to
multiply the chain.
python -m doctest -v matrix_chain_multiply.py

Given a sequence ``arr[]`` that represents chain of 2D matrices such that the dimension
of the ``i`` th matrix is ``arr[i-1]*arr[i]``.
So suppose ``arr = [40, 20, 30, 10, 30]`` means we have ``4`` matrices of dimensions
``40*20``, ``20*30``, ``30*10`` and ``10*30``.

``matrix_chain_multiply()`` returns an integer denoting minimum number of
multiplications to multiply the chain.

We do not need to perform actual multiplication here.
We only need to decide the order in which to perform the multiplication.

Hints:
1. Number of multiplications (ie cost) to multiply 2 matrices
of size m*p and p*n is m*p*n.
2. Cost of matrix multiplication is associative ie (M1*M2)*M3 != M1*(M2*M3)
3. Matrix multiplication is not commutative. So, M1*M2 does not mean M2*M1 can be done.
4. To determine the required order, we can try different combinations.
1. Number of multiplications (ie cost) to multiply ``2`` matrices
of size ``m*p`` and ``p*n`` is ``m*p*n``.
2. Cost of matrix multiplication is not associative ie ``(M1*M2)*M3 != M1*(M2*M3)``
3. Matrix multiplication is not commutative. So, ``M1*M2`` does not mean ``M2*M1``
can be done.
4. To determine the required order, we can try different combinations.

So, this problem has overlapping sub-problems and can be solved using recursion.
We use Dynamic Programming for optimal time complexity.

Example input:
arr = [40, 20, 30, 10, 30]
output: 26000
``arr = [40, 20, 30, 10, 30]``
output:
``26000``
"""

from collections.abc import Iterator
Expand All @@ -50,25 +56,25 @@ def matrix_chain_multiply(arr: list[int]) -> int:
Find the minimum number of multiplcations required to multiply the chain of matrices

Args:
arr: The input array of integers.
`arr`: The input array of integers.

Returns:
Minimum number of multiplications needed to multiply the chain

Examples:
>>> matrix_chain_multiply([1, 2, 3, 4, 3])
30
>>> matrix_chain_multiply([10])
0
>>> matrix_chain_multiply([10, 20])
0
>>> matrix_chain_multiply([19, 2, 19])
722
>>> matrix_chain_multiply(list(range(1, 100)))
323398

# >>> matrix_chain_multiply(list(range(1, 251)))
# 2626798

>>> matrix_chain_multiply([1, 2, 3, 4, 3])
30
>>> matrix_chain_multiply([10])
0
>>> matrix_chain_multiply([10, 20])
0
>>> matrix_chain_multiply([19, 2, 19])
722
>>> matrix_chain_multiply(list(range(1, 100)))
323398
>>> # matrix_chain_multiply(list(range(1, 251)))
# 2626798
"""
if len(arr) < 2:
return 0
Expand All @@ -93,8 +99,10 @@ def matrix_chain_multiply(arr: list[int]) -> int:
def matrix_chain_order(dims: list[int]) -> int:
"""
Source: https://en.wikipedia.org/wiki/Matrix_chain_multiplication

The dynamic programming solution is faster than cached the recursive solution and
can handle larger inputs.

>>> matrix_chain_order([1, 2, 3, 4, 3])
30
>>> matrix_chain_order([10])
Expand All @@ -105,8 +113,7 @@ def matrix_chain_order(dims: list[int]) -> int:
722
>>> matrix_chain_order(list(range(1, 100)))
323398

# >>> matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised
>>> # matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised
# 2626798
"""

Expand Down
3 changes: 2 additions & 1 deletion dynamic_programming/max_product_subarray.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
def max_product_subarray(numbers: list[int]) -> int:
"""
Returns the maximum product that can be obtained by multiplying a
contiguous subarray of the given integer list `nums`.
contiguous subarray of the given integer list `numbers`.

Example:

>>> max_product_subarray([2, 3, -2, 4])
6
>>> max_product_subarray((-2, 0, -1))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
def minimum_squares_to_represent_a_number(number: int) -> int:
"""
Count the number of minimum squares to represent a number

>>> minimum_squares_to_represent_a_number(25)
1
>>> minimum_squares_to_represent_a_number(37)
Expand Down
22 changes: 12 additions & 10 deletions dynamic_programming/regex_match.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
"""
Regex matching check if a text matches pattern or not.
Pattern:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.

1. ``.`` Matches any single character.
2. ``*`` Matches zero or more of the preceding element.

More info:
https://medium.com/trick-the-interviwer/regular-expression-matching-9972eb74c03
"""


def recursive_match(text: str, pattern: str) -> bool:
"""
r"""
Recursive matching algorithm.

Time complexity: O(2 ^ (|text| + |pattern|))
Space complexity: Recursion depth is O(|text| + |pattern|).
| Time complexity: O(2^(\|text\| + \|pattern\|))
| Space complexity: Recursion depth is O(\|text\| + \|pattern\|).

:param text: Text to match.
:param pattern: Pattern to match.
:return: True if text matches pattern, False otherwise.
:return: ``True`` if `text` matches `pattern`, ``False`` otherwise.

>>> recursive_match('abc', 'a.c')
True
Expand Down Expand Up @@ -48,15 +50,15 @@ def recursive_match(text: str, pattern: str) -> bool:


def dp_match(text: str, pattern: str) -> bool:
"""
r"""
Dynamic programming matching algorithm.

Time complexity: O(|text| * |pattern|)
Space complexity: O(|text| * |pattern|)
| Time complexity: O(\|text\| * \|pattern\|)
| Space complexity: O(\|text\| * \|pattern\|)

:param text: Text to match.
:param pattern: Pattern to match.
:return: True if text matches pattern, False otherwise.
:return: ``True`` if `text` matches `pattern`, ``False`` otherwise.

>>> dp_match('abc', 'a.c')
True
Expand Down
Loading
Loading