mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 18:38:39 +00:00
Merge branch 'TheAlgorithms:master' into master
This commit is contained in:
commit
9776f93dc9
2
.github/pull_request_template.md
vendored
2
.github/pull_request_template.md
vendored
@ -17,4 +17,4 @@
|
|||||||
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
|
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
|
||||||
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
|
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
|
||||||
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
|
* [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
|
||||||
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|
* [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
|
||||||
|
6
.github/workflows/build.yml
vendored
6
.github/workflows/build.yml
vendored
@ -22,11 +22,9 @@ jobs:
|
|||||||
python -m pip install --upgrade pip setuptools six wheel
|
python -m pip install --upgrade pip setuptools six wheel
|
||||||
python -m pip install pytest-cov -r requirements.txt
|
python -m pip install pytest-cov -r requirements.txt
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
# See: #6591 for re-enabling tests on Python v3.11
|
# TODO: #8818 Re-enable quantum tests
|
||||||
run: pytest
|
run: pytest
|
||||||
--ignore=computer_vision/cnn_classification.py
|
--ignore=quantum/q_fourier_transform.py
|
||||||
--ignore=machine_learning/lstm/lstm_prediction.py
|
|
||||||
--ignore=quantum/
|
|
||||||
--ignore=project_euler/
|
--ignore=project_euler/
|
||||||
--ignore=scripts/validate_solutions.py
|
--ignore=scripts/validate_solutions.py
|
||||||
--cov-report=term-missing:skip-covered
|
--cov-report=term-missing:skip-covered
|
||||||
|
@ -15,8 +15,8 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: auto-walrus
|
- id: auto-walrus
|
||||||
|
|
||||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: v0.0.272
|
rev: v0.0.275
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
|
|
||||||
@ -33,7 +33,7 @@ repos:
|
|||||||
- tomli
|
- tomli
|
||||||
|
|
||||||
- repo: https://github.com/tox-dev/pyproject-fmt
|
- repo: https://github.com/tox-dev/pyproject-fmt
|
||||||
rev: "0.12.0"
|
rev: "0.12.1"
|
||||||
hooks:
|
hooks:
|
||||||
- id: pyproject-fmt
|
- id: pyproject-fmt
|
||||||
|
|
||||||
@ -51,7 +51,7 @@ repos:
|
|||||||
- id: validate-pyproject
|
- id: validate-pyproject
|
||||||
|
|
||||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
rev: v1.3.0
|
rev: v1.4.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
args:
|
args:
|
||||||
|
@ -25,7 +25,12 @@ We appreciate any contribution, from fixing a grammar mistake in a comment to im
|
|||||||
|
|
||||||
Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help.
|
Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help.
|
||||||
|
|
||||||
Please help us keep our issue list small by adding fixes: #{$ISSUE_NO} to the commit message of pull requests that resolve open issues. GitHub will use this tag to auto-close the issue when the PR is merged.
|
Please help us keep our issue list small by adding `Fixes #{$ISSUE_NUMBER}` to the description of pull requests that resolve open issues.
|
||||||
|
For example, if your pull request fixes issue #10, then please add the following to its description:
|
||||||
|
```
|
||||||
|
Fixes #10
|
||||||
|
```
|
||||||
|
GitHub will use this tag to [auto-close the issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if and when the PR is merged.
|
||||||
|
|
||||||
#### What is an Algorithm?
|
#### What is an Algorithm?
|
||||||
|
|
||||||
|
@ -29,6 +29,7 @@
|
|||||||
* [Minmax](backtracking/minmax.py)
|
* [Minmax](backtracking/minmax.py)
|
||||||
* [N Queens](backtracking/n_queens.py)
|
* [N Queens](backtracking/n_queens.py)
|
||||||
* [N Queens Math](backtracking/n_queens_math.py)
|
* [N Queens Math](backtracking/n_queens_math.py)
|
||||||
|
* [Power Sum](backtracking/power_sum.py)
|
||||||
* [Rat In Maze](backtracking/rat_in_maze.py)
|
* [Rat In Maze](backtracking/rat_in_maze.py)
|
||||||
* [Sudoku](backtracking/sudoku.py)
|
* [Sudoku](backtracking/sudoku.py)
|
||||||
* [Sum Of Subsets](backtracking/sum_of_subsets.py)
|
* [Sum Of Subsets](backtracking/sum_of_subsets.py)
|
||||||
@ -146,6 +147,7 @@
|
|||||||
* [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py)
|
* [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py)
|
||||||
* [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py)
|
* [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py)
|
||||||
* [Decimal To Octal](conversions/decimal_to_octal.py)
|
* [Decimal To Octal](conversions/decimal_to_octal.py)
|
||||||
|
* [Energy Conversions](conversions/energy_conversions.py)
|
||||||
* [Excel Title To Column](conversions/excel_title_to_column.py)
|
* [Excel Title To Column](conversions/excel_title_to_column.py)
|
||||||
* [Hex To Bin](conversions/hex_to_bin.py)
|
* [Hex To Bin](conversions/hex_to_bin.py)
|
||||||
* [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py)
|
* [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py)
|
||||||
@ -166,6 +168,7 @@
|
|||||||
* Arrays
|
* Arrays
|
||||||
* [Permutations](data_structures/arrays/permutations.py)
|
* [Permutations](data_structures/arrays/permutations.py)
|
||||||
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
|
* [Prefix Sum](data_structures/arrays/prefix_sum.py)
|
||||||
|
* [Product Sum](data_structures/arrays/product_sum.py)
|
||||||
* Binary Tree
|
* Binary Tree
|
||||||
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
|
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
|
||||||
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
|
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
|
||||||
@ -410,6 +413,7 @@
|
|||||||
* [Dijkstra 2](graphs/dijkstra_2.py)
|
* [Dijkstra 2](graphs/dijkstra_2.py)
|
||||||
* [Dijkstra Algorithm](graphs/dijkstra_algorithm.py)
|
* [Dijkstra Algorithm](graphs/dijkstra_algorithm.py)
|
||||||
* [Dijkstra Alternate](graphs/dijkstra_alternate.py)
|
* [Dijkstra Alternate](graphs/dijkstra_alternate.py)
|
||||||
|
* [Dijkstra Binary Grid](graphs/dijkstra_binary_grid.py)
|
||||||
* [Dinic](graphs/dinic.py)
|
* [Dinic](graphs/dinic.py)
|
||||||
* [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py)
|
* [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py)
|
||||||
* [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py)
|
* [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py)
|
||||||
@ -519,7 +523,6 @@
|
|||||||
* [Xgboost Regressor](machine_learning/xgboost_regressor.py)
|
* [Xgboost Regressor](machine_learning/xgboost_regressor.py)
|
||||||
|
|
||||||
## Maths
|
## Maths
|
||||||
* [3N Plus 1](maths/3n_plus_1.py)
|
|
||||||
* [Abs](maths/abs.py)
|
* [Abs](maths/abs.py)
|
||||||
* [Add](maths/add.py)
|
* [Add](maths/add.py)
|
||||||
* [Addition Without Arithmetic](maths/addition_without_arithmetic.py)
|
* [Addition Without Arithmetic](maths/addition_without_arithmetic.py)
|
||||||
|
93
backtracking/power_sum.py
Normal file
93
backtracking/power_sum.py
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
"""
|
||||||
|
Problem source: https://www.hackerrank.com/challenges/the-power-sum/problem
|
||||||
|
Find the number of ways that a given integer X, can be expressed as the sum
|
||||||
|
of the Nth powers of unique, natural numbers. For example, if X=13 and N=2.
|
||||||
|
We have to find all combinations of unique squares adding up to 13.
|
||||||
|
The only solution is 2^2+3^2. Constraints: 1<=X<=1000, 2<=N<=10.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from math import pow
|
||||||
|
|
||||||
|
|
||||||
|
def backtrack(
|
||||||
|
needed_sum: int,
|
||||||
|
power: int,
|
||||||
|
current_number: int,
|
||||||
|
current_sum: int,
|
||||||
|
solutions_count: int,
|
||||||
|
) -> tuple[int, int]:
|
||||||
|
"""
|
||||||
|
>>> backtrack(13, 2, 1, 0, 0)
|
||||||
|
(0, 1)
|
||||||
|
>>> backtrack(100, 2, 1, 0, 0)
|
||||||
|
(0, 3)
|
||||||
|
>>> backtrack(100, 3, 1, 0, 0)
|
||||||
|
(0, 1)
|
||||||
|
>>> backtrack(800, 2, 1, 0, 0)
|
||||||
|
(0, 561)
|
||||||
|
>>> backtrack(1000, 10, 1, 0, 0)
|
||||||
|
(0, 0)
|
||||||
|
>>> backtrack(400, 2, 1, 0, 0)
|
||||||
|
(0, 55)
|
||||||
|
>>> backtrack(50, 1, 1, 0, 0)
|
||||||
|
(0, 3658)
|
||||||
|
"""
|
||||||
|
if current_sum == needed_sum:
|
||||||
|
# If the sum of the powers is equal to needed_sum, then we have a solution.
|
||||||
|
solutions_count += 1
|
||||||
|
return current_sum, solutions_count
|
||||||
|
|
||||||
|
i_to_n = int(pow(current_number, power))
|
||||||
|
if current_sum + i_to_n <= needed_sum:
|
||||||
|
# If the sum of the powers is less than needed_sum, then continue adding powers.
|
||||||
|
current_sum += i_to_n
|
||||||
|
current_sum, solutions_count = backtrack(
|
||||||
|
needed_sum, power, current_number + 1, current_sum, solutions_count
|
||||||
|
)
|
||||||
|
current_sum -= i_to_n
|
||||||
|
if i_to_n < needed_sum:
|
||||||
|
# If the power of i is less than needed_sum, then try with the next power.
|
||||||
|
current_sum, solutions_count = backtrack(
|
||||||
|
needed_sum, power, current_number + 1, current_sum, solutions_count
|
||||||
|
)
|
||||||
|
return current_sum, solutions_count
|
||||||
|
|
||||||
|
|
||||||
|
def solve(needed_sum: int, power: int) -> int:
|
||||||
|
"""
|
||||||
|
>>> solve(13, 2)
|
||||||
|
1
|
||||||
|
>>> solve(100, 2)
|
||||||
|
3
|
||||||
|
>>> solve(100, 3)
|
||||||
|
1
|
||||||
|
>>> solve(800, 2)
|
||||||
|
561
|
||||||
|
>>> solve(1000, 10)
|
||||||
|
0
|
||||||
|
>>> solve(400, 2)
|
||||||
|
55
|
||||||
|
>>> solve(50, 1)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Invalid input
|
||||||
|
needed_sum must be between 1 and 1000, power between 2 and 10.
|
||||||
|
>>> solve(-10, 5)
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Invalid input
|
||||||
|
needed_sum must be between 1 and 1000, power between 2 and 10.
|
||||||
|
"""
|
||||||
|
if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
|
||||||
|
raise ValueError(
|
||||||
|
"Invalid input\n"
|
||||||
|
"needed_sum must be between 1 and 1000, power between 2 and 10."
|
||||||
|
)
|
||||||
|
|
||||||
|
return backtrack(needed_sum, power, 1, 0, 0)[1] # Return the solutions_count
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
114
conversions/energy_conversions.py
Normal file
114
conversions/energy_conversions.py
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
"""
|
||||||
|
Conversion of energy units.
|
||||||
|
|
||||||
|
Available units: joule, kilojoule, megajoule, gigajoule,\
|
||||||
|
wattsecond, watthour, kilowatthour, newtonmeter, calorie_nutr,\
|
||||||
|
kilocalorie_nutr, electronvolt, britishthermalunit_it, footpound
|
||||||
|
|
||||||
|
USAGE :
|
||||||
|
-> Import this file into their respective project.
|
||||||
|
-> Use the function energy_conversion() for conversion of energy units.
|
||||||
|
-> Parameters :
|
||||||
|
-> from_type : From which type you want to convert
|
||||||
|
-> to_type : To which type you want to convert
|
||||||
|
-> value : the value which you want to convert
|
||||||
|
|
||||||
|
REFERENCES :
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Units_of_energy
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Joule
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilowatt-hour
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Newton-metre
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Calorie
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Electronvolt
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/British_thermal_unit
|
||||||
|
-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot-pound_(energy)
|
||||||
|
-> Unit converter reference: https://www.unitconverters.net/energy-converter.html
|
||||||
|
"""
|
||||||
|
|
||||||
|
ENERGY_CONVERSION: dict[str, float] = {
|
||||||
|
"joule": 1.0,
|
||||||
|
"kilojoule": 1_000,
|
||||||
|
"megajoule": 1_000_000,
|
||||||
|
"gigajoule": 1_000_000_000,
|
||||||
|
"wattsecond": 1.0,
|
||||||
|
"watthour": 3_600,
|
||||||
|
"kilowatthour": 3_600_000,
|
||||||
|
"newtonmeter": 1.0,
|
||||||
|
"calorie_nutr": 4_186.8,
|
||||||
|
"kilocalorie_nutr": 4_186_800.00,
|
||||||
|
"electronvolt": 1.602_176_634e-19,
|
||||||
|
"britishthermalunit_it": 1_055.055_85,
|
||||||
|
"footpound": 1.355_818,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def energy_conversion(from_type: str, to_type: str, value: float) -> float:
|
||||||
|
"""
|
||||||
|
Conversion of energy units.
|
||||||
|
>>> energy_conversion("joule", "joule", 1)
|
||||||
|
1.0
|
||||||
|
>>> energy_conversion("joule", "kilojoule", 1)
|
||||||
|
0.001
|
||||||
|
>>> energy_conversion("joule", "megajoule", 1)
|
||||||
|
1e-06
|
||||||
|
>>> energy_conversion("joule", "gigajoule", 1)
|
||||||
|
1e-09
|
||||||
|
>>> energy_conversion("joule", "wattsecond", 1)
|
||||||
|
1.0
|
||||||
|
>>> energy_conversion("joule", "watthour", 1)
|
||||||
|
0.0002777777777777778
|
||||||
|
>>> energy_conversion("joule", "kilowatthour", 1)
|
||||||
|
2.7777777777777776e-07
|
||||||
|
>>> energy_conversion("joule", "newtonmeter", 1)
|
||||||
|
1.0
|
||||||
|
>>> energy_conversion("joule", "calorie_nutr", 1)
|
||||||
|
0.00023884589662749592
|
||||||
|
>>> energy_conversion("joule", "kilocalorie_nutr", 1)
|
||||||
|
2.388458966274959e-07
|
||||||
|
>>> energy_conversion("joule", "electronvolt", 1)
|
||||||
|
6.241509074460763e+18
|
||||||
|
>>> energy_conversion("joule", "britishthermalunit_it", 1)
|
||||||
|
0.0009478171226670134
|
||||||
|
>>> energy_conversion("joule", "footpound", 1)
|
||||||
|
0.7375621211696556
|
||||||
|
>>> energy_conversion("joule", "megajoule", 1000)
|
||||||
|
0.001
|
||||||
|
>>> energy_conversion("calorie_nutr", "kilocalorie_nutr", 1000)
|
||||||
|
1.0
|
||||||
|
>>> energy_conversion("kilowatthour", "joule", 10)
|
||||||
|
36000000.0
|
||||||
|
>>> energy_conversion("britishthermalunit_it", "footpound", 1)
|
||||||
|
778.1692306784539
|
||||||
|
>>> energy_conversion("watthour", "joule", "a") # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
TypeError: unsupported operand type(s) for /: 'str' and 'float'
|
||||||
|
>>> energy_conversion("wrongunit", "joule", 1) # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Incorrect 'from_type' or 'to_type' value: 'wrongunit', 'joule'
|
||||||
|
Valid values are: joule, ... footpound
|
||||||
|
>>> energy_conversion("joule", "wrongunit", 1) # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Incorrect 'from_type' or 'to_type' value: 'joule', 'wrongunit'
|
||||||
|
Valid values are: joule, ... footpound
|
||||||
|
>>> energy_conversion("123", "abc", 1) # doctest: +ELLIPSIS
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: Incorrect 'from_type' or 'to_type' value: '123', 'abc'
|
||||||
|
Valid values are: joule, ... footpound
|
||||||
|
"""
|
||||||
|
if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:
|
||||||
|
msg = (
|
||||||
|
f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
|
||||||
|
f"Valid values are: {', '.join(ENERGY_CONVERSION)}"
|
||||||
|
)
|
||||||
|
raise ValueError(msg)
|
||||||
|
return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
98
data_structures/arrays/product_sum.py
Normal file
98
data_structures/arrays/product_sum.py
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
"""
|
||||||
|
Calculate the Product Sum from a Special Array.
|
||||||
|
reference: https://dev.to/sfrasica/algorithms-product-sum-from-an-array-dc6
|
||||||
|
|
||||||
|
Python doctests can be run with the following command:
|
||||||
|
python -m doctest -v product_sum.py
|
||||||
|
|
||||||
|
Calculate the product sum of a "special" array which can contain integers or nested
|
||||||
|
arrays. The product sum is obtained by adding all elements and multiplying by their
|
||||||
|
respective depths.
|
||||||
|
|
||||||
|
For example, in the array [x, y], the product sum is (x + y). In the array [x, [y, z]],
|
||||||
|
the product sum is x + 2 * (y + z). In the array [x, [y, [z]]],
|
||||||
|
the product sum is x + 2 * (y + 3z).
|
||||||
|
|
||||||
|
Example Input:
|
||||||
|
[5, 2, [-7, 1], 3, [6, [-13, 8], 4]]
|
||||||
|
Output: 12
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def product_sum(arr: list[int | list], depth: int) -> int:
|
||||||
|
"""
|
||||||
|
Recursively calculates the product sum of an array.
|
||||||
|
|
||||||
|
The product sum of an array is defined as the sum of its elements multiplied by
|
||||||
|
their respective depths. If an element is a list, its product sum is calculated
|
||||||
|
recursively by multiplying the sum of its elements with its depth plus one.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
arr: The array of integers and nested lists.
|
||||||
|
depth: The current depth level.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: The product sum of the array.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> product_sum([1, 2, 3], 1)
|
||||||
|
6
|
||||||
|
>>> product_sum([-1, 2, [-3, 4]], 2)
|
||||||
|
8
|
||||||
|
>>> product_sum([1, 2, 3], -1)
|
||||||
|
-6
|
||||||
|
>>> product_sum([1, 2, 3], 0)
|
||||||
|
0
|
||||||
|
>>> product_sum([1, 2, 3], 7)
|
||||||
|
42
|
||||||
|
>>> product_sum((1, 2, 3), 7)
|
||||||
|
42
|
||||||
|
>>> product_sum({1, 2, 3}, 7)
|
||||||
|
42
|
||||||
|
>>> product_sum([1, -1], 1)
|
||||||
|
0
|
||||||
|
>>> product_sum([1, -2], 1)
|
||||||
|
-1
|
||||||
|
>>> product_sum([-3.5, [1, [0.5]]], 1)
|
||||||
|
1.5
|
||||||
|
|
||||||
|
"""
|
||||||
|
total_sum = 0
|
||||||
|
for ele in arr:
|
||||||
|
total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele
|
||||||
|
return total_sum * depth
|
||||||
|
|
||||||
|
|
||||||
|
def product_sum_array(array: list[int | list]) -> int:
|
||||||
|
"""
|
||||||
|
Calculates the product sum of an array.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
array (List[Union[int, List]]): The array of integers and nested lists.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
int: The product sum of the array.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
>>> product_sum_array([1, 2, 3])
|
||||||
|
6
|
||||||
|
>>> product_sum_array([1, [2, 3]])
|
||||||
|
11
|
||||||
|
>>> product_sum_array([1, [2, [3, 4]]])
|
||||||
|
47
|
||||||
|
>>> product_sum_array([0])
|
||||||
|
0
|
||||||
|
>>> product_sum_array([-3.5, [1, [0.5]]])
|
||||||
|
1.5
|
||||||
|
>>> product_sum_array([1, -2])
|
||||||
|
-1
|
||||||
|
|
||||||
|
"""
|
||||||
|
return product_sum(array, 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
@ -32,7 +32,7 @@ class Deque:
|
|||||||
the number of nodes
|
the number of nodes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = ["_front", "_back", "_len"]
|
__slots__ = ("_front", "_back", "_len")
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class _Node:
|
class _Node:
|
||||||
@ -54,7 +54,7 @@ class Deque:
|
|||||||
the current node of the iteration.
|
the current node of the iteration.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = ["_cur"]
|
__slots__ = "_cur"
|
||||||
|
|
||||||
def __init__(self, cur: Deque._Node | None) -> None:
|
def __init__(self, cur: Deque._Node | None) -> None:
|
||||||
self._cur = cur
|
self._cur = cur
|
||||||
|
89
graphs/dijkstra_binary_grid.py
Normal file
89
graphs/dijkstra_binary_grid.py
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
"""
|
||||||
|
This script implements the Dijkstra algorithm on a binary grid.
|
||||||
|
The grid consists of 0s and 1s, where 1 represents
|
||||||
|
a walkable node and 0 represents an obstacle.
|
||||||
|
The algorithm finds the shortest path from a start node to a destination node.
|
||||||
|
Diagonal movement can be allowed or disallowed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from heapq import heappop, heappush
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
def dijkstra(
|
||||||
|
grid: np.ndarray,
|
||||||
|
source: tuple[int, int],
|
||||||
|
destination: tuple[int, int],
|
||||||
|
allow_diagonal: bool,
|
||||||
|
) -> tuple[float | int, list[tuple[int, int]]]:
|
||||||
|
"""
|
||||||
|
Implements Dijkstra's algorithm on a binary grid.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
grid (np.ndarray): A 2D numpy array representing the grid.
|
||||||
|
1 represents a walkable node and 0 represents an obstacle.
|
||||||
|
source (Tuple[int, int]): A tuple representing the start node.
|
||||||
|
destination (Tuple[int, int]): A tuple representing the
|
||||||
|
destination node.
|
||||||
|
allow_diagonal (bool): A boolean determining whether
|
||||||
|
diagonal movements are allowed.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple[Union[float, int], List[Tuple[int, int]]]:
|
||||||
|
The shortest distance from the start node to the destination node
|
||||||
|
and the shortest path as a list of nodes.
|
||||||
|
|
||||||
|
>>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), False)
|
||||||
|
(4.0, [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)])
|
||||||
|
|
||||||
|
>>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), True)
|
||||||
|
(2.0, [(0, 0), (1, 1), (2, 2)])
|
||||||
|
|
||||||
|
>>> dijkstra(np.array([[1, 1, 1], [0, 0, 1], [0, 1, 1]]), (0, 0), (2, 2), False)
|
||||||
|
(4.0, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])
|
||||||
|
"""
|
||||||
|
rows, cols = grid.shape
|
||||||
|
dx = [-1, 1, 0, 0]
|
||||||
|
dy = [0, 0, -1, 1]
|
||||||
|
if allow_diagonal:
|
||||||
|
dx += [-1, -1, 1, 1]
|
||||||
|
dy += [-1, 1, -1, 1]
|
||||||
|
|
||||||
|
queue, visited = [(0, source)], set()
|
||||||
|
matrix = np.full((rows, cols), np.inf)
|
||||||
|
matrix[source] = 0
|
||||||
|
predecessors = np.empty((rows, cols), dtype=object)
|
||||||
|
predecessors[source] = None
|
||||||
|
|
||||||
|
while queue:
|
||||||
|
(dist, (x, y)) = heappop(queue)
|
||||||
|
if (x, y) in visited:
|
||||||
|
continue
|
||||||
|
visited.add((x, y))
|
||||||
|
|
||||||
|
if (x, y) == destination:
|
||||||
|
path = []
|
||||||
|
while (x, y) != source:
|
||||||
|
path.append((x, y))
|
||||||
|
x, y = predecessors[x, y]
|
||||||
|
path.append(source) # add the source manually
|
||||||
|
path.reverse()
|
||||||
|
return matrix[destination], path
|
||||||
|
|
||||||
|
for i in range(len(dx)):
|
||||||
|
nx, ny = x + dx[i], y + dy[i]
|
||||||
|
if 0 <= nx < rows and 0 <= ny < cols:
|
||||||
|
next_node = grid[nx][ny]
|
||||||
|
if next_node == 1 and matrix[nx, ny] > dist + 1:
|
||||||
|
heappush(queue, (dist + 1, (nx, ny)))
|
||||||
|
matrix[nx, ny] = dist + 1
|
||||||
|
predecessors[nx, ny] = (x, y)
|
||||||
|
|
||||||
|
return np.inf, []
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import doctest
|
||||||
|
|
||||||
|
doctest.testmod()
|
@ -1,151 +0,0 @@
|
|||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
|
|
||||||
def n31(a: int) -> tuple[list[int], int]:
|
|
||||||
"""
|
|
||||||
Returns the Collatz sequence and its length of any positive integer.
|
|
||||||
>>> n31(4)
|
|
||||||
([4, 2, 1], 3)
|
|
||||||
"""
|
|
||||||
|
|
||||||
if not isinstance(a, int):
|
|
||||||
msg = f"Must be int, not {type(a).__name__}"
|
|
||||||
raise TypeError(msg)
|
|
||||||
if a < 1:
|
|
||||||
msg = f"Given integer must be positive, not {a}"
|
|
||||||
raise ValueError(msg)
|
|
||||||
|
|
||||||
path = [a]
|
|
||||||
while a != 1:
|
|
||||||
if a % 2 == 0:
|
|
||||||
a //= 2
|
|
||||||
else:
|
|
||||||
a = 3 * a + 1
|
|
||||||
path.append(a)
|
|
||||||
return path, len(path)
|
|
||||||
|
|
||||||
|
|
||||||
def test_n31():
|
|
||||||
"""
|
|
||||||
>>> test_n31()
|
|
||||||
"""
|
|
||||||
assert n31(4) == ([4, 2, 1], 3)
|
|
||||||
assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15)
|
|
||||||
assert n31(31) == (
|
|
||||||
[
|
|
||||||
31,
|
|
||||||
94,
|
|
||||||
47,
|
|
||||||
142,
|
|
||||||
71,
|
|
||||||
214,
|
|
||||||
107,
|
|
||||||
322,
|
|
||||||
161,
|
|
||||||
484,
|
|
||||||
242,
|
|
||||||
121,
|
|
||||||
364,
|
|
||||||
182,
|
|
||||||
91,
|
|
||||||
274,
|
|
||||||
137,
|
|
||||||
412,
|
|
||||||
206,
|
|
||||||
103,
|
|
||||||
310,
|
|
||||||
155,
|
|
||||||
466,
|
|
||||||
233,
|
|
||||||
700,
|
|
||||||
350,
|
|
||||||
175,
|
|
||||||
526,
|
|
||||||
263,
|
|
||||||
790,
|
|
||||||
395,
|
|
||||||
1186,
|
|
||||||
593,
|
|
||||||
1780,
|
|
||||||
890,
|
|
||||||
445,
|
|
||||||
1336,
|
|
||||||
668,
|
|
||||||
334,
|
|
||||||
167,
|
|
||||||
502,
|
|
||||||
251,
|
|
||||||
754,
|
|
||||||
377,
|
|
||||||
1132,
|
|
||||||
566,
|
|
||||||
283,
|
|
||||||
850,
|
|
||||||
425,
|
|
||||||
1276,
|
|
||||||
638,
|
|
||||||
319,
|
|
||||||
958,
|
|
||||||
479,
|
|
||||||
1438,
|
|
||||||
719,
|
|
||||||
2158,
|
|
||||||
1079,
|
|
||||||
3238,
|
|
||||||
1619,
|
|
||||||
4858,
|
|
||||||
2429,
|
|
||||||
7288,
|
|
||||||
3644,
|
|
||||||
1822,
|
|
||||||
911,
|
|
||||||
2734,
|
|
||||||
1367,
|
|
||||||
4102,
|
|
||||||
2051,
|
|
||||||
6154,
|
|
||||||
3077,
|
|
||||||
9232,
|
|
||||||
4616,
|
|
||||||
2308,
|
|
||||||
1154,
|
|
||||||
577,
|
|
||||||
1732,
|
|
||||||
866,
|
|
||||||
433,
|
|
||||||
1300,
|
|
||||||
650,
|
|
||||||
325,
|
|
||||||
976,
|
|
||||||
488,
|
|
||||||
244,
|
|
||||||
122,
|
|
||||||
61,
|
|
||||||
184,
|
|
||||||
92,
|
|
||||||
46,
|
|
||||||
23,
|
|
||||||
70,
|
|
||||||
35,
|
|
||||||
106,
|
|
||||||
53,
|
|
||||||
160,
|
|
||||||
80,
|
|
||||||
40,
|
|
||||||
20,
|
|
||||||
10,
|
|
||||||
5,
|
|
||||||
16,
|
|
||||||
8,
|
|
||||||
4,
|
|
||||||
2,
|
|
||||||
1,
|
|
||||||
],
|
|
||||||
107,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
num = 4
|
|
||||||
path, length = n31(num)
|
|
||||||
print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
|
|
@ -1,43 +1,66 @@
|
|||||||
|
"""
|
||||||
|
The Collatz conjecture is a famous unsolved problem in mathematics. Given a starting
|
||||||
|
positive integer, define the following sequence:
|
||||||
|
- If the current term n is even, then the next term is n/2.
|
||||||
|
- If the current term n is odd, then the next term is 3n + 1.
|
||||||
|
The conjecture claims that this sequence will always reach 1 for any starting number.
|
||||||
|
|
||||||
|
Other names for this problem include the 3n + 1 problem, the Ulam conjecture, Kakutani's
|
||||||
|
problem, the Thwaites conjecture, Hasse's algorithm, the Syracuse problem, and the
|
||||||
|
hailstone sequence.
|
||||||
|
|
||||||
|
Reference: https://en.wikipedia.org/wiki/Collatz_conjecture
|
||||||
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Generator
|
||||||
|
|
||||||
def collatz_sequence(n: int) -> list[int]:
|
|
||||||
|
def collatz_sequence(n: int) -> Generator[int, None, None]:
|
||||||
"""
|
"""
|
||||||
Collatz conjecture: start with any positive integer n. The next term is
|
Generate the Collatz sequence starting at n.
|
||||||
obtained as follows:
|
>>> tuple(collatz_sequence(2.1))
|
||||||
If n term is even, the next term is: n / 2 .
|
|
||||||
If n is odd, the next term is: 3 * n + 1.
|
|
||||||
|
|
||||||
The conjecture states the sequence will always reach 1 for any starting value n.
|
|
||||||
Example:
|
|
||||||
>>> collatz_sequence(2.1)
|
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
Exception: Sequence only defined for natural numbers
|
Exception: Sequence only defined for positive integers
|
||||||
>>> collatz_sequence(0)
|
>>> tuple(collatz_sequence(0))
|
||||||
Traceback (most recent call last):
|
Traceback (most recent call last):
|
||||||
...
|
...
|
||||||
Exception: Sequence only defined for natural numbers
|
Exception: Sequence only defined for positive integers
|
||||||
>>> collatz_sequence(43) # doctest: +NORMALIZE_WHITESPACE
|
>>> tuple(collatz_sequence(4))
|
||||||
[43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7,
|
(4, 2, 1)
|
||||||
22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
|
>>> tuple(collatz_sequence(11))
|
||||||
|
(11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1)
|
||||||
|
>>> tuple(collatz_sequence(31)) # doctest: +NORMALIZE_WHITESPACE
|
||||||
|
(31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137,
|
||||||
|
412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593,
|
||||||
|
1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425,
|
||||||
|
1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644,
|
||||||
|
1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732,
|
||||||
|
866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53,
|
||||||
|
160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1)
|
||||||
|
>>> tuple(collatz_sequence(43)) # doctest: +NORMALIZE_WHITESPACE
|
||||||
|
(43, 130, 65, 196, 98, 49, 148, 74, 37, 112, 56, 28, 14, 7, 22, 11, 34, 17, 52, 26,
|
||||||
|
13, 40, 20, 10, 5, 16, 8, 4, 2, 1)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not isinstance(n, int) or n < 1:
|
if not isinstance(n, int) or n < 1:
|
||||||
raise Exception("Sequence only defined for natural numbers")
|
raise Exception("Sequence only defined for positive integers")
|
||||||
|
|
||||||
sequence = [n]
|
yield n
|
||||||
while n != 1:
|
while n != 1:
|
||||||
n = 3 * n + 1 if n & 1 else n // 2
|
if n % 2 == 0:
|
||||||
sequence.append(n)
|
n //= 2
|
||||||
return sequence
|
else:
|
||||||
|
n = 3 * n + 1
|
||||||
|
yield n
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
n = 43
|
n = 43
|
||||||
sequence = collatz_sequence(n)
|
sequence = tuple(collatz_sequence(n))
|
||||||
print(sequence)
|
print(sequence)
|
||||||
print(f"collatz sequence from {n} took {len(sequence)} steps.")
|
print(f"Collatz sequence from {n} took {len(sequence)} steps.")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
@ -67,7 +67,7 @@ def benchmark():
|
|||||||
|
|
||||||
|
|
||||||
class TestLeastCommonMultiple(unittest.TestCase):
|
class TestLeastCommonMultiple(unittest.TestCase):
|
||||||
test_inputs = [
|
test_inputs = (
|
||||||
(10, 20),
|
(10, 20),
|
||||||
(13, 15),
|
(13, 15),
|
||||||
(4, 31),
|
(4, 31),
|
||||||
@ -77,8 +77,8 @@ class TestLeastCommonMultiple(unittest.TestCase):
|
|||||||
(12, 25),
|
(12, 25),
|
||||||
(10, 25),
|
(10, 25),
|
||||||
(6, 9),
|
(6, 9),
|
||||||
]
|
)
|
||||||
expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18]
|
expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18)
|
||||||
|
|
||||||
def test_lcm_function(self):
|
def test_lcm_function(self):
|
||||||
for i, (first_num, second_num) in enumerate(self.test_inputs):
|
for i, (first_num, second_num) in enumerate(self.test_inputs):
|
||||||
|
@ -17,7 +17,7 @@ This script is inspired by a corresponding research paper.
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
def sigmoid(vector: np.array) -> np.array:
|
def sigmoid(vector: np.ndarray) -> np.ndarray:
|
||||||
"""
|
"""
|
||||||
Mathematical function sigmoid takes a vector x of K real numbers as input and
|
Mathematical function sigmoid takes a vector x of K real numbers as input and
|
||||||
returns 1/ (1 + e^-x).
|
returns 1/ (1 + e^-x).
|
||||||
@ -29,17 +29,15 @@ def sigmoid(vector: np.array) -> np.array:
|
|||||||
return 1 / (1 + np.exp(-vector))
|
return 1 / (1 + np.exp(-vector))
|
||||||
|
|
||||||
|
|
||||||
def sigmoid_linear_unit(vector: np.array) -> np.array:
|
def sigmoid_linear_unit(vector: np.ndarray) -> np.ndarray:
|
||||||
"""
|
"""
|
||||||
Implements the Sigmoid Linear Unit (SiLU) or swish function
|
Implements the Sigmoid Linear Unit (SiLU) or swish function
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
vector (np.array): A numpy array consisting of real
|
vector (np.ndarray): A numpy array consisting of real values
|
||||||
values.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
swish_vec (np.array): The input numpy array, after applying
|
swish_vec (np.ndarray): The input numpy array, after applying swish
|
||||||
swish.
|
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
>>> sigmoid_linear_unit(np.array([-1.0, 1.0, 2.0]))
|
>>> sigmoid_linear_unit(np.array([-1.0, 1.0, 2.0]))
|
||||||
|
@ -47,18 +47,18 @@ import os
|
|||||||
|
|
||||||
class PokerHand:
|
class PokerHand:
|
||||||
"""Create an object representing a Poker Hand based on an input of a
|
"""Create an object representing a Poker Hand based on an input of a
|
||||||
string which represents the best 5 card combination from the player's hand
|
string which represents the best 5-card combination from the player's hand
|
||||||
and board cards.
|
and board cards.
|
||||||
|
|
||||||
Attributes: (read-only)
|
Attributes: (read-only)
|
||||||
hand: string representing the hand consisting of five cards
|
hand: a string representing the hand consisting of five cards
|
||||||
|
|
||||||
Methods:
|
Methods:
|
||||||
compare_with(opponent): takes in player's hand (self) and
|
compare_with(opponent): takes in player's hand (self) and
|
||||||
opponent's hand (opponent) and compares both hands according to
|
opponent's hand (opponent) and compares both hands according to
|
||||||
the rules of Texas Hold'em.
|
the rules of Texas Hold'em.
|
||||||
Returns one of 3 strings (Win, Loss, Tie) based on whether
|
Returns one of 3 strings (Win, Loss, Tie) based on whether
|
||||||
player's hand is better than opponent's hand.
|
player's hand is better than the opponent's hand.
|
||||||
|
|
||||||
hand_name(): Returns a string made up of two parts: hand name
|
hand_name(): Returns a string made up of two parts: hand name
|
||||||
and high card.
|
and high card.
|
||||||
@ -66,11 +66,11 @@ class PokerHand:
|
|||||||
Supported operators:
|
Supported operators:
|
||||||
Rich comparison operators: <, >, <=, >=, ==, !=
|
Rich comparison operators: <, >, <=, >=, ==, !=
|
||||||
|
|
||||||
Supported builtin methods and functions:
|
Supported built-in methods and functions:
|
||||||
list.sort(), sorted()
|
list.sort(), sorted()
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_HAND_NAME = [
|
_HAND_NAME = (
|
||||||
"High card",
|
"High card",
|
||||||
"One pair",
|
"One pair",
|
||||||
"Two pairs",
|
"Two pairs",
|
||||||
@ -81,10 +81,10 @@ class PokerHand:
|
|||||||
"Four of a kind",
|
"Four of a kind",
|
||||||
"Straight flush",
|
"Straight flush",
|
||||||
"Royal flush",
|
"Royal flush",
|
||||||
]
|
)
|
||||||
|
|
||||||
_CARD_NAME = [
|
_CARD_NAME = (
|
||||||
"", # placeholder as lists are zero indexed
|
"", # placeholder as tuples are zero-indexed
|
||||||
"One",
|
"One",
|
||||||
"Two",
|
"Two",
|
||||||
"Three",
|
"Three",
|
||||||
@ -99,7 +99,7 @@ class PokerHand:
|
|||||||
"Queen",
|
"Queen",
|
||||||
"King",
|
"King",
|
||||||
"Ace",
|
"Ace",
|
||||||
]
|
)
|
||||||
|
|
||||||
def __init__(self, hand: str) -> None:
|
def __init__(self, hand: str) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -103,6 +103,7 @@ max-complexity = 17 # default: 10
|
|||||||
"machine_learning/linear_discriminant_analysis.py" = ["ARG005"]
|
"machine_learning/linear_discriminant_analysis.py" = ["ARG005"]
|
||||||
"machine_learning/sequential_minimum_optimization.py" = ["SIM115"]
|
"machine_learning/sequential_minimum_optimization.py" = ["SIM115"]
|
||||||
"matrix/sherman_morrison.py" = ["SIM103", "SIM114"]
|
"matrix/sherman_morrison.py" = ["SIM103", "SIM114"]
|
||||||
|
"other/l*u_cache.py" = ["RUF012"]
|
||||||
"physics/newtons_second_law_of_motion.py" = ["BLE001"]
|
"physics/newtons_second_law_of_motion.py" = ["BLE001"]
|
||||||
"project_euler/problem_099/sol1.py" = ["SIM115"]
|
"project_euler/problem_099/sol1.py" = ["SIM115"]
|
||||||
"sorts/external_sort.py" = ["SIM115"]
|
"sorts/external_sort.py" = ["SIM115"]
|
||||||
|
@ -64,10 +64,10 @@ def bb84(key_len: int = 8, seed: int | None = None) -> str:
|
|||||||
key: The key generated using BB84 protocol.
|
key: The key generated using BB84 protocol.
|
||||||
|
|
||||||
>>> bb84(16, seed=0)
|
>>> bb84(16, seed=0)
|
||||||
'1101101100010000'
|
'0111110111010010'
|
||||||
|
|
||||||
>>> bb84(8, seed=0)
|
>>> bb84(8, seed=0)
|
||||||
'01011011'
|
'10110001'
|
||||||
"""
|
"""
|
||||||
# Set up the random number generator.
|
# Set up the random number generator.
|
||||||
rng = np.random.default_rng(seed=seed)
|
rng = np.random.default_rng(seed=seed)
|
||||||
|
Loading…
x
Reference in New Issue
Block a user