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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
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
1 change: 0 additions & 1 deletion DIRECTORY.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -710,7 +710,6 @@
* [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Input Data](neural_network/input_data.py)
* [Perceptron](neural_network/perceptron.py)
* [Simple Neural Network](neural_network/simple_neural_network.py)

Expand Down
30 changes: 19 additions & 11 deletions conversions/length_conversion.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -22,9 +22,13 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Millimeter
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

TYPE_CONVERSION = {
"millimeter": "mm",
Expand All@@ -40,14 +44,14 @@
}

METRIC_CONVERSION = {
"mm": from_to(0.001, 1000),
"cm": from_to(0.01, 100),
"m": from_to(1, 1),
"km": from_to(1000, 0.001),
"in": from_to(0.0254, 39.3701),
"ft": from_to(0.3048, 3.28084),
"yd": from_to(0.9144, 1.09361),
"mi": from_to(1609.34, 0.000621371),
"mm": FromTo(0.001, 1000),
"cm": FromTo(0.01, 100),
"m": FromTo(1, 1),
"km": FromTo(1000, 0.001),
"in": FromTo(0.0254, 39.3701),
"ft": FromTo(0.3048, 3.28084),
"yd": FromTo(0.9144, 1.09361),
"mi": FromTo(1609.34, 0.000621371),
}


Expand DownExpand Up@@ -115,7 +119,11 @@ def length_conversion(value: float, from_type: str, to_type: str) -> float:
f"Conversion abbreviations are: {', '.join(METRIC_CONVERSION)}"
)
raise ValueError(msg)
return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to
return (
value
* METRIC_CONVERSION[new_from].from_factor
* METRIC_CONVERSION[new_to].to_factor
)


if __name__ == "__main__":
Expand Down
28 changes: 17 additions & 11 deletions conversions/pressure_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,19 +19,23 @@
-> https://www.unitconverters.net/pressure-converter.html
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

PRESSURE_CONVERSION = {
"atm": from_to(1, 1),
"pascal": from_to(0.0000098, 101325),
"bar": from_to(0.986923, 1.01325),
"kilopascal": from_to(0.00986923, 101.325),
"megapascal": from_to(9.86923, 0.101325),
"psi": from_to(0.068046, 14.6959),
"inHg": from_to(0.0334211, 29.9213),
"torr": from_to(0.00131579, 760),
"atm": FromTo(1, 1),
"pascal": FromTo(0.0000098, 101325),
"bar": FromTo(0.986923, 1.01325),
"kilopascal": FromTo(0.00986923, 101.325),
"megapascal": FromTo(9.86923, 0.101325),
"psi": FromTo(0.068046, 14.6959),
"inHg": FromTo(0.0334211, 29.9213),
"torr": FromTo(0.00131579, 760),
}


Expand DownExpand Up@@ -71,7 +75,9 @@ def pressure_conversion(value: float, from_type: str, to_type: str) -> float:
+ ", ".join(PRESSURE_CONVERSION)
)
return (
value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
value
* PRESSURE_CONVERSION[from_type].from_factor
* PRESSURE_CONVERSION[to_type].to_factor
)


Expand Down
40 changes: 24 additions & 16 deletions conversions/volume_conversions.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -18,43 +18,47 @@
-> Wikipedia reference: https://en.wikipedia.org/wiki/Cup_(unit)
"""

from collections import namedtuple
from typing import NamedTuple


class FromTo(NamedTuple):
from_factor: float
to_factor: float

from_to = namedtuple("from_to", "from_ to")

METRIC_CONVERSION = {
"cubicmeter": from_to(1, 1),
"litre": from_to(0.001, 1000),
"kilolitre": from_to(1, 1),
"gallon": from_to(0.00454, 264.172),
"cubicyard": from_to(0.76455, 1.30795),
"cubicfoot": from_to(0.028, 35.3147),
"cup": from_to(0.000236588, 4226.75),
"cubic meter": FromTo(1, 1),
"litre": FromTo(0.001, 1000),
"kilolitre": FromTo(1, 1),
"gallon": FromTo(0.00454, 264.172),
"cubic yard": FromTo(0.76455, 1.30795),
"cubic foot": FromTo(0.028, 35.3147),
"cup": FromTo(0.000236588, 4226.75),
}


def volume_conversion(value: float, from_type: str, to_type: str) -> float:
"""
Conversion between volume units.
>>> volume_conversion(4, "cubicmeter", "litre")
>>> volume_conversion(4, "cubic meter", "litre")
4000
>>> volume_conversion(1, "litre", "gallon")
0.264172
>>> volume_conversion(1, "kilolitre", "cubicmeter")
>>> volume_conversion(1, "kilolitre", "cubic meter")
1
>>> volume_conversion(3, "gallon", "cubicyard")
>>> volume_conversion(3, "gallon", "cubic yard")
0.017814279
>>> volume_conversion(2, "cubicyard", "litre")
>>> volume_conversion(2, "cubic yard", "litre")
1529.1
>>> volume_conversion(4, "cubicfoot", "cup")
>>> volume_conversion(4, "cubic foot", "cup")
473.396
>>> volume_conversion(1, "cup", "kilolitre")
0.000236588
>>> volume_conversion(4, "wrongUnit", "litre")
Traceback (most recent call last):
...
ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are:
cubicmeter, litre, kilolitre, gallon, cubicyard, cubicfoot, cup
cubic meter, litre, kilolitre, gallon, cubic yard, cubic foot, cup
"""
if from_type not in METRIC_CONVERSION:
raise ValueError(
Expand All@@ -66,7 +70,11 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float:
f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n"
+ ", ".join(METRIC_CONVERSION)
)
return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to
return (
value
* METRIC_CONVERSION[from_type].from_factor
* METRIC_CONVERSION[to_type].to_factor
)


if __name__ == "__main__":
Expand Down
10 changes: 6 additions & 4 deletions data_structures/binary_tree/distribute_coins.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -39,8 +39,8 @@

from __future__ import annotations

from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple


@dataclass
Expand All@@ -50,7 +50,9 @@ class TreeNode:
right: TreeNode | None = None


CoinsDistribResult = namedtuple("CoinsDistribResult", "moves excess")
class CoinsDistribResult(NamedTuple):
moves: int
excess: int


def distribute_coins(root: TreeNode | None) -> int:
Expand DownExpand Up@@ -79,7 +81,7 @@ def distribute_coins(root: TreeNode | None) -> int:
# Validation
def count_nodes(node: TreeNode | None) -> int:
"""
>>> count_nodes(None):
>>> count_nodes(None)
0
"""
if node is None:
Expand All@@ -89,7 +91,7 @@ def count_nodes(node: TreeNode | None) -> int:

def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:
Expand Down
22 changes: 13 additions & 9 deletions electronics/electric_power.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
# https://en.m.wikipedia.org/wiki/Electric_power
from __future__ import annotations

from collections import namedtuple
from typing import NamedTuple


class Result(NamedTuple):
name: str
value: float


def electric_power(voltage: float, current: float, power: float) -> tuple:
Expand All@@ -10,11 +15,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
fundamental value of electrical system.
examples are below:
>>> electric_power(voltage=0, current=2, power=5)
result(name='voltage', value=2.5)
Result(name='voltage', value=2.5)
>>> electric_power(voltage=2, current=2, power=0)
result(name='power', value=4.0)
Result(name='power', value=4.0)
>>> electric_power(voltage=-2, current=3, power=0)
result(name='power', value=6.0)
Result(name='power', value=6.0)
>>> electric_power(voltage=2, current=4, power=2)
Traceback (most recent call last):
...
Expand All@@ -28,21 +33,20 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
...
ValueError: Power cannot be negative in any electrical/electronics system
>>> electric_power(voltage=2.2, current=2.2, power=0)
result(name='power', value=4.84)
Result(name='power', value=4.84)
"""
result = namedtuple("result", "name value")
if (voltage, current, power).count(0) != 1:
raise ValueError("Only one argument must be 0")
elif power < 0:
raise ValueError(
"Power cannot be negative in any electrical/electronics system"
)
elif voltage == 0:
return result("voltage", power / current)
return Result("voltage", power / current)
elif current == 0:
return result("current", power / voltage)
return Result("current", power / voltage)
elif power == 0:
return result("power", float(round(abs(voltage * current), 2)))
return Result("power", float(round(abs(voltage * current), 2)))
else:
raise ValueError("Exactly one argument must be 0")

Expand Down
4 changes: 2 additions & 2 deletions graphs/bi_directional_dijkstra.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -26,8 +26,8 @@ def pass_and_relaxation(
cst_bwd: dict,
queue: PriorityQueue,
parent: dict,
shortest_distance: float | int,
) -> float | int:
shortest_distance: float,
) -> float:
for nxt, d in graph[v]:
if nxt in visited_forward:
continue
Expand Down
6 changes: 3 additions & 3 deletions maths/area_under_curve.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
2 changes: 1 addition & 1 deletion maths/decimal_to_fraction.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
def decimal_to_fraction(decimal: int | float | str) -> tuple[int, int]:
def decimal_to_fraction(decimal: float | str) -> tuple[int, int]:
"""
Return a decimal number in its simplest fraction form
>>> decimal_to_fraction(2)
Expand Down
6 changes: 3 additions & 3 deletions maths/line_length.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -5,9 +5,9 @@


def line_length(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
6 changes: 3 additions & 3 deletions maths/numerical_integration.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,9 +7,9 @@


def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
fnc: Callable[[float], float],
x_start: float,
x_end: float,
steps: int = 100,
) -> float:
"""
Expand Down
4 changes: 2 additions & 2 deletions maths/polynomials/single_indeterminate_operations.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -87,7 +87,7 @@ def __mul__(self, polynomial_2: Polynomial) -> Polynomial:

return Polynomial(self.degree + polynomial_2.degree, coefficients)

def evaluate(self, substitution: int | float) -> int | float:
def evaluate(self, substitution: float) -> float:
"""
Evaluates the polynomial at x.
>>> p = Polynomial(2, [1, 2, 3])
Expand DownExpand Up@@ -144,7 +144,7 @@ def derivative(self) -> Polynomial:
coefficients[i] = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1, coefficients)

def integral(self, constant: int | float = 0) -> Polynomial:
def integral(self, constant: float = 0) -> Polynomial:
"""
Returns the integral of the polynomial.
>>> p = Polynomial(2, [1, 2, 3])
Expand Down
10 changes: 5 additions & 5 deletions maths/series/geometric_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -14,10 +14,10 @@


def geometric_series(
nth_term: float | int,
start_term_a: float | int,
common_ratio_r: float | int,
) -> list[float | int]:
nth_term: float,
start_term_a: float,
common_ratio_r: float,
) -> list[float]:
"""
Pure Python implementation of Geometric Series algorithm

Expand DownExpand Up@@ -48,7 +48,7 @@ def geometric_series(
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[float | int] = []
series: list[float] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
Expand Down
2 changes: 1 addition & 1 deletion maths/series/p_series.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,7 +13,7 @@
from __future__ import annotations


def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]:
def p_series(nth_term: float | str, power: float | str) -> list[str]:
"""
Pure Python implementation of P-Series algorithm
:return: The P-Series starting from 1 to last (nth) term
Expand Down
2 changes: 1 addition & 1 deletion maths/volume.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -8,7 +8,7 @@
from math import pi, pow


def vol_cube(side_length: int | float) -> float:
def vol_cube(side_length: float) -> float:
"""
Calculate the Volume of a Cube.
>>> vol_cube(1)
Expand Down
Loading