Skip to content

Commit 7fa9b4b

Browse files
Fix sphinx/build_docs warnings for dynamic_programming (#12484)
* Fix sphinx/build_docs warnings for dynamic_programming * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix * Fix * Fix * Fix * Fix * Fix --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 493a7c1 commit 7fa9b4b

13 files changed

+295
-286
lines changed

dynamic_programming/all_construct.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88

99
def all_construct(target: str, word_bank: list[str] | None = None) -> list[list[str]]:
1010
"""
11-
returns the list containing all the possible
12-
combinations a string(target) can be constructed from
13-
the given list of substrings(word_bank)
11+
returns the list containing all the possible
12+
combinations a string(`target`) can be constructed from
13+
the given list of substrings(`word_bank`)
14+
1415
>>> all_construct("hello", ["he", "l", "o"])
1516
[['he', 'l', 'l', 'o']]
1617
>>> all_construct("purple",["purp","p","ur","le","purpl"])

dynamic_programming/combination_sum_iv.py

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
11
"""
22
Question:
3-
You are given an array of distinct integers and you have to tell how many
4-
different ways of selecting the elements from the array are there such that
5-
the sum of chosen elements is equal to the target number tar.
3+
You are given an array of distinct integers and you have to tell how many
4+
different ways of selecting the elements from the array are there such that
5+
the sum of chosen elements is equal to the target number tar.
66
77
Example
88
99
Input:
10-
N = 3
11-
target = 5
12-
array = [1, 2, 5]
10+
* N = 3
11+
* target = 5
12+
* array = [1, 2, 5]
1313
1414
Output:
15-
9
15+
9
1616
1717
Approach:
18-
The basic idea is to go over recursively to find the way such that the sum
19-
of chosen elements is “tar”. For every element, we have two choices
20-
1. Include the element in our set of chosen elements.
21-
2. Don't include the element in our set of chosen elements.
18+
The basic idea is to go over recursively to find the way such that the sum
19+
of chosen elements is `target`. For every element, we have two choices
20+
21+
1. Include the element in our set of chosen elements.
22+
2. Don't include the element in our set of chosen elements.
2223
"""
2324

2425

dynamic_programming/fizz_buzz.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33

44
def fizz_buzz(number: int, iterations: int) -> str:
55
"""
6-
Plays FizzBuzz.
7-
Prints Fizz if number is a multiple of 3.
8-
Prints Buzz if its a multiple of 5.
9-
Prints FizzBuzz if its a multiple of both 3 and 5 or 15.
10-
Else Prints The Number Itself.
6+
| Plays FizzBuzz.
7+
| Prints Fizz if number is a multiple of ``3``.
8+
| Prints Buzz if its a multiple of ``5``.
9+
| Prints FizzBuzz if its a multiple of both ``3`` and ``5`` or ``15``.
10+
| Else Prints The Number Itself.
11+
1112
>>> fizz_buzz(1,7)
1213
'1 2 Fizz 4 Buzz Fizz 7 '
1314
>>> fizz_buzz(1,0)

dynamic_programming/knapsack.py

+21-19
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ def mf_knapsack(i, wt, val, j):
1111
"""
1212
This code involves the concept of memory functions. Here we solve the subproblems
1313
which are needed unlike the below example
14-
F is a 2D array with -1s filled up
14+
F is a 2D array with ``-1`` s filled up
1515
"""
1616
global f # a global dp table for knapsack
1717
if f[i][j] < 0:
@@ -45,22 +45,24 @@ def knapsack_with_example_solution(w: int, wt: list, val: list):
4545
the several possible optimal subsets.
4646
4747
Parameters
48-
---------
48+
----------
4949
50-
W: int, the total maximum weight for the given knapsack problem.
51-
wt: list, the vector of weights for all items where wt[i] is the weight
52-
of the i-th item.
53-
val: list, the vector of values for all items where val[i] is the value
54-
of the i-th item
50+
* `w`: int, the total maximum weight for the given knapsack problem.
51+
* `wt`: list, the vector of weights for all items where ``wt[i]`` is the weight
52+
of the ``i``-th item.
53+
* `val`: list, the vector of values for all items where ``val[i]`` is the value
54+
of the ``i``-th item
5555
5656
Returns
5757
-------
58-
optimal_val: float, the optimal value for the given knapsack problem
59-
example_optional_set: set, the indices of one of the optimal subsets
60-
which gave rise to the optimal value.
58+
59+
* `optimal_val`: float, the optimal value for the given knapsack problem
60+
* `example_optional_set`: set, the indices of one of the optimal subsets
61+
which gave rise to the optimal value.
6162
6263
Examples
63-
-------
64+
--------
65+
6466
>>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22])
6567
(142, {2, 3, 4})
6668
>>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4])
@@ -104,19 +106,19 @@ def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set):
104106
a filled DP table and the vector of weights
105107
106108
Parameters
107-
---------
108-
109-
dp: list of list, the table of a solved integer weight dynamic programming problem
109+
----------
110110
111-
wt: list or tuple, the vector of weights of the items
112-
i: int, the index of the item under consideration
113-
j: int, the current possible maximum weight
114-
optimal_set: set, the optimal subset so far. This gets modified by the function.
111+
* `dp`: list of list, the table of a solved integer weight dynamic programming
112+
problem
113+
* `wt`: list or tuple, the vector of weights of the items
114+
* `i`: int, the index of the item under consideration
115+
* `j`: int, the current possible maximum weight
116+
* `optimal_set`: set, the optimal subset so far. This gets modified by the function.
115117
116118
Returns
117119
-------
118-
None
119120
121+
``None``
120122
"""
121123
# for the current item i at a maximum weight j to be part of an optimal subset,
122124
# the optimal value at (i, j) must be greater than the optimal value at (i-1, j).

dynamic_programming/longest_common_substring.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
"""
2-
Longest Common Substring Problem Statement: Given two sequences, find the
3-
longest common substring present in both of them. A substring is
4-
necessarily continuous.
5-
Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de".
6-
Therefore, algorithm should return any one of them.
2+
Longest Common Substring Problem Statement:
3+
Given two sequences, find the
4+
longest common substring present in both of them. A substring is
5+
necessarily continuous.
6+
7+
Example:
8+
``abcdef`` and ``xabded`` have two longest common substrings, ``ab`` or ``de``.
9+
Therefore, algorithm should return any one of them.
710
"""
811

912

1013
def longest_common_substring(text1: str, text2: str) -> str:
1114
"""
1215
Finds the longest common substring between two strings.
16+
1317
>>> longest_common_substring("", "")
1418
''
1519
>>> longest_common_substring("a","")

dynamic_programming/longest_increasing_subsequence.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@
44
This is a pure Python implementation of Dynamic Programming solution to the longest
55
increasing subsequence of a given sequence.
66
7-
The problem is :
8-
Given an array, to find the longest and increasing sub-array in that given array and
9-
return it.
10-
Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return
11-
[10, 22, 33, 41, 60, 80] as output
7+
The problem is:
8+
Given an array, to find the longest and increasing sub-array in that given array and
9+
return it.
10+
11+
Example:
12+
``[10, 22, 9, 33, 21, 50, 41, 60, 80]`` as input will return
13+
``[10, 22, 33, 41, 60, 80]`` as output
1214
"""
1315

1416
from __future__ import annotations
@@ -17,6 +19,7 @@
1719
def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive
1820
"""
1921
Some examples
22+
2023
>>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80])
2124
[10, 22, 33, 41, 60, 80]
2225
>>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9])

dynamic_programming/matrix_chain_multiplication.py

+48-41
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,48 @@
11
"""
2-
Find the minimum number of multiplications needed to multiply chain of matrices.
3-
Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
2+
| Find the minimum number of multiplications needed to multiply chain of matrices.
3+
| Reference: https://www.geeksforgeeks.org/matrix-chain-multiplication-dp-8/
44
5-
The algorithm has interesting real-world applications. Example:
6-
1. Image transformations in Computer Graphics as images are composed of matrix.
7-
2. Solve complex polynomial equations in the field of algebra using least processing
8-
power.
9-
3. Calculate overall impact of macroeconomic decisions as economic equations involve a
10-
number of variables.
11-
4. Self-driving car navigation can be made more accurate as matrix multiplication can
12-
accurately determine position and orientation of obstacles in short time.
5+
The algorithm has interesting real-world applications.
136
14-
Python doctests can be run with the following command:
15-
python -m doctest -v matrix_chain_multiply.py
7+
Example:
8+
1. Image transformations in Computer Graphics as images are composed of matrix.
9+
2. Solve complex polynomial equations in the field of algebra using least processing
10+
power.
11+
3. Calculate overall impact of macroeconomic decisions as economic equations involve a
12+
number of variables.
13+
4. Self-driving car navigation can be made more accurate as matrix multiplication can
14+
accurately determine position and orientation of obstacles in short time.
1615
17-
Given a sequence arr[] that represents chain of 2D matrices such that the dimension of
18-
the ith matrix is arr[i-1]*arr[i].
19-
So suppose arr = [40, 20, 30, 10, 30] means we have 4 matrices of dimensions
20-
40*20, 20*30, 30*10 and 10*30.
16+
Python doctests can be run with the following command::
2117
22-
matrix_chain_multiply() returns an integer denoting minimum number of multiplications to
23-
multiply the chain.
18+
python -m doctest -v matrix_chain_multiply.py
19+
20+
Given a sequence ``arr[]`` that represents chain of 2D matrices such that the dimension
21+
of the ``i`` th matrix is ``arr[i-1]*arr[i]``.
22+
So suppose ``arr = [40, 20, 30, 10, 30]`` means we have ``4`` matrices of dimensions
23+
``40*20``, ``20*30``, ``30*10`` and ``10*30``.
24+
25+
``matrix_chain_multiply()`` returns an integer denoting minimum number of
26+
multiplications to multiply the chain.
2427
2528
We do not need to perform actual multiplication here.
2629
We only need to decide the order in which to perform the multiplication.
2730
2831
Hints:
29-
1. Number of multiplications (ie cost) to multiply 2 matrices
30-
of size m*p and p*n is m*p*n.
31-
2. Cost of matrix multiplication is associative ie (M1*M2)*M3 != M1*(M2*M3)
32-
3. Matrix multiplication is not commutative. So, M1*M2 does not mean M2*M1 can be done.
33-
4. To determine the required order, we can try different combinations.
32+
1. Number of multiplications (ie cost) to multiply ``2`` matrices
33+
of size ``m*p`` and ``p*n`` is ``m*p*n``.
34+
2. Cost of matrix multiplication is not associative ie ``(M1*M2)*M3 != M1*(M2*M3)``
35+
3. Matrix multiplication is not commutative. So, ``M1*M2`` does not mean ``M2*M1``
36+
can be done.
37+
4. To determine the required order, we can try different combinations.
38+
3439
So, this problem has overlapping sub-problems and can be solved using recursion.
3540
We use Dynamic Programming for optimal time complexity.
3641
3742
Example input:
38-
arr = [40, 20, 30, 10, 30]
39-
output: 26000
43+
``arr = [40, 20, 30, 10, 30]``
44+
output:
45+
``26000``
4046
"""
4147

4248
from collections.abc import Iterator
@@ -50,25 +56,25 @@ def matrix_chain_multiply(arr: list[int]) -> int:
5056
Find the minimum number of multiplcations required to multiply the chain of matrices
5157
5258
Args:
53-
arr: The input array of integers.
59+
`arr`: The input array of integers.
5460
5561
Returns:
5662
Minimum number of multiplications needed to multiply the chain
5763
5864
Examples:
59-
>>> matrix_chain_multiply([1, 2, 3, 4, 3])
60-
30
61-
>>> matrix_chain_multiply([10])
62-
0
63-
>>> matrix_chain_multiply([10, 20])
64-
0
65-
>>> matrix_chain_multiply([19, 2, 19])
66-
722
67-
>>> matrix_chain_multiply(list(range(1, 100)))
68-
323398
69-
70-
# >>> matrix_chain_multiply(list(range(1, 251)))
71-
# 2626798
65+
66+
>>> matrix_chain_multiply([1, 2, 3, 4, 3])
67+
30
68+
>>> matrix_chain_multiply([10])
69+
0
70+
>>> matrix_chain_multiply([10, 20])
71+
0
72+
>>> matrix_chain_multiply([19, 2, 19])
73+
722
74+
>>> matrix_chain_multiply(list(range(1, 100)))
75+
323398
76+
>>> # matrix_chain_multiply(list(range(1, 251)))
77+
# 2626798
7278
"""
7379
if len(arr) < 2:
7480
return 0
@@ -93,8 +99,10 @@ def matrix_chain_multiply(arr: list[int]) -> int:
9399
def matrix_chain_order(dims: list[int]) -> int:
94100
"""
95101
Source: https://en.wikipedia.org/wiki/Matrix_chain_multiplication
102+
96103
The dynamic programming solution is faster than cached the recursive solution and
97104
can handle larger inputs.
105+
98106
>>> matrix_chain_order([1, 2, 3, 4, 3])
99107
30
100108
>>> matrix_chain_order([10])
@@ -105,8 +113,7 @@ def matrix_chain_order(dims: list[int]) -> int:
105113
722
106114
>>> matrix_chain_order(list(range(1, 100)))
107115
323398
108-
109-
# >>> matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised
116+
>>> # matrix_chain_order(list(range(1, 251))) # Max before RecursionError is raised
110117
# 2626798
111118
"""
112119

dynamic_programming/max_product_subarray.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
def max_product_subarray(numbers: list[int]) -> int:
22
"""
33
Returns the maximum product that can be obtained by multiplying a
4-
contiguous subarray of the given integer list `nums`.
4+
contiguous subarray of the given integer list `numbers`.
55
66
Example:
7+
78
>>> max_product_subarray([2, 3, -2, 4])
89
6
910
>>> max_product_subarray((-2, 0, -1))

dynamic_programming/minimum_squares_to_represent_a_number.py

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
def minimum_squares_to_represent_a_number(number: int) -> int:
66
"""
77
Count the number of minimum squares to represent a number
8+
89
>>> minimum_squares_to_represent_a_number(25)
910
1
1011
>>> minimum_squares_to_represent_a_number(37)

dynamic_programming/regex_match.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
"""
22
Regex matching check if a text matches pattern or not.
33
Pattern:
4-
'.' Matches any single character.
5-
'*' Matches zero or more of the preceding element.
4+
5+
1. ``.`` Matches any single character.
6+
2. ``*`` Matches zero or more of the preceding element.
7+
68
More info:
79
https://medium.com/trick-the-interviwer/regular-expression-matching-9972eb74c03
810
"""
911

1012

1113
def recursive_match(text: str, pattern: str) -> bool:
12-
"""
14+
r"""
1315
Recursive matching algorithm.
1416
15-
Time complexity: O(2 ^ (|text| + |pattern|))
16-
Space complexity: Recursion depth is O(|text| + |pattern|).
17+
| Time complexity: O(2^(\|text\| + \|pattern\|))
18+
| Space complexity: Recursion depth is O(\|text\| + \|pattern\|).
1719
1820
:param text: Text to match.
1921
:param pattern: Pattern to match.
20-
:return: True if text matches pattern, False otherwise.
22+
:return: ``True`` if `text` matches `pattern`, ``False`` otherwise.
2123
2224
>>> recursive_match('abc', 'a.c')
2325
True
@@ -48,15 +50,15 @@ def recursive_match(text: str, pattern: str) -> bool:
4850

4951

5052
def dp_match(text: str, pattern: str) -> bool:
51-
"""
53+
r"""
5254
Dynamic programming matching algorithm.
5355
54-
Time complexity: O(|text| * |pattern|)
55-
Space complexity: O(|text| * |pattern|)
56+
| Time complexity: O(\|text\| * \|pattern\|)
57+
| Space complexity: O(\|text\| * \|pattern\|)
5658
5759
:param text: Text to match.
5860
:param pattern: Pattern to match.
59-
:return: True if text matches pattern, False otherwise.
61+
:return: ``True`` if `text` matches `pattern`, ``False`` otherwise.
6062
6163
>>> dp_match('abc', 'a.c')
6264
True

0 commit comments

Comments
 (0)