Fix ruff errors (#8936)

* Fix ruff errors

Renamed neural_network/input_data.py to neural_network/input_data.py_tf
because it should be left out of the directory for the following
reasons:

1. Its sole purpose is to be used by neural_network/gan.py_tf, which is
   itself left out of the directory because of issues with TensorFlow.

2. It was taken directly from TensorFlow's codebase and is actually
   already deprecated. If/when neural_network/gan.py_tf is eventually
   re-added back to the directory, its implementation should be changed
   to not use neural_network/input_data.py anyway.

* updating DIRECTORY.md

* Change input_data.py_tf file extension

Change input_data.py_tf file extension because algorithms-keeper bot is being picky about it

---------

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Tianyi Zheng 2023-08-09 00:55:30 -07:00 committed by GitHub
parent 842d03fb2a
commit ae0fc85401
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 121 additions and 94 deletions

View File

@ -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)

View File

@ -22,9 +22,13 @@ REFERENCES :
-> 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",
@ -40,14 +44,14 @@ TYPE_CONVERSION = {
}
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),
}
@ -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__":

View File

@ -19,19 +19,23 @@ REFERENCES :
-> 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),
}
@ -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
)

View File

@ -18,18 +18,22 @@ REFERENCES :
-> 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),
}
@ -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__":

View File

@ -39,8 +39,8 @@ Space: O(1)
from __future__ import annotations
from collections import namedtuple
from dataclasses import dataclass
from typing import NamedTuple
@dataclass
@ -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:
@ -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:
@ -89,7 +91,7 @@ def distribute_coins(root: TreeNode | None) -> int:
def count_coins(node: TreeNode | None) -> int:
"""
>>> count_coins(None):
>>> count_coins(None)
0
"""
if node is None:

View File

@ -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:
@ -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):
...
@ -28,9 +33,8 @@ 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:
@ -38,11 +42,11 @@ def electric_power(voltage: float, current: float, power: float) -> tuple:
"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")

View File

@ -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

View File

@ -7,9 +7,9 @@ from collections.abc import Callable
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:
"""

View File

@ -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)

View File

@ -5,9 +5,9 @@ from collections.abc import Callable
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:
"""

View File

@ -7,9 +7,9 @@ from collections.abc import Callable
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:
"""

View File

@ -87,7 +87,7 @@ class 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])
@ -144,7 +144,7 @@ class 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])

View File

@ -14,10 +14,10 @@ from __future__ import annotations
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
@ -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)):

View File

@ -13,7 +13,7 @@ python3 p_series.py
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

View File

@ -8,7 +8,7 @@ from __future__ import annotations
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)

View File

@ -141,7 +141,7 @@ class Matrix:
@property
def order(self) -> tuple[int, int]:
return (self.num_rows, self.num_columns)
return self.num_rows, self.num_columns
@property
def is_square(self) -> bool:
@ -315,7 +315,7 @@ class Matrix:
]
)
def __mul__(self, other: Matrix | int | float) -> Matrix:
def __mul__(self, other: Matrix | float) -> Matrix:
if isinstance(other, (int, float)):
return Matrix(
[[int(element * other) for element in row] for row in self.rows]

View File

@ -47,7 +47,7 @@ def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[
raise TypeError("Expected a matrix, got int/list instead")
def scalar_multiply(matrix: list[list[int]], n: int | float) -> list[list[float]]:
def scalar_multiply(matrix: list[list[int]], n: float) -> list[list[float]]:
"""
>>> scalar_multiply([[1,2],[3,4]],5)
[[5, 10], [15, 20]]
@ -189,9 +189,7 @@ def main() -> None:
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
)
print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n")
print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")

View File

@ -1,9 +1,7 @@
from __future__ import annotations
def search_in_a_sorted_matrix(
mat: list[list[int]], m: int, n: int, key: int | float
) -> None:
def search_in_a_sorted_matrix(mat: list[list[int]], m: int, n: int, key: float) -> None:
"""
>>> search_in_a_sorted_matrix(
... [[2, 5, 7], [4, 8, 13], [9, 11, 15], [12, 17, 20]], 3, 3, 5)

View File

@ -22,7 +22,7 @@ class Matrix:
"""
self.row, self.column = row, column
self.array = [[default_value for c in range(column)] for r in range(row)]
self.array = [[default_value for _ in range(column)] for _ in range(row)]
def __str__(self) -> str:
"""
@ -54,15 +54,15 @@ class Matrix:
def __repr__(self) -> str:
return str(self)
def validate_indicies(self, loc: tuple[int, int]) -> bool:
def validate_indices(self, loc: tuple[int, int]) -> bool:
"""
<method Matrix.validate_indicies>
Check if given indices are valid to pick element from matrix.
Example:
>>> a = Matrix(2, 6, 0)
>>> a.validate_indicies((2, 7))
>>> a.validate_indices((2, 7))
False
>>> a.validate_indicies((0, 0))
>>> a.validate_indices((0, 0))
True
"""
if not (isinstance(loc, (list, tuple)) and len(loc) == 2):
@ -81,7 +81,7 @@ class Matrix:
>>> a[1, 0]
7
"""
assert self.validate_indicies(loc)
assert self.validate_indices(loc)
return self.array[loc[0]][loc[1]]
def __setitem__(self, loc: tuple[int, int], value: float) -> None:
@ -96,7 +96,7 @@ class Matrix:
[ 1, 1, 1]
[ 1, 1, 51]
"""
assert self.validate_indicies(loc)
assert self.validate_indices(loc)
self.array[loc[0]][loc[1]] = value
def __add__(self, another: Matrix) -> Matrix:
@ -145,7 +145,7 @@ class Matrix:
def __sub__(self, another: Matrix) -> Matrix:
return self + (-another)
def __mul__(self, another: int | float | Matrix) -> Matrix:
def __mul__(self, another: float | Matrix) -> Matrix:
"""
<method Matrix.__mul__>
Return self * another.
@ -233,7 +233,7 @@ class Matrix:
v_t = v.transpose()
numerator_factor = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return None # It's not invertible
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))

View File

@ -4,17 +4,21 @@ This is to show simple COVID19 info fetching from worldometers site using lxml
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
from typing import NamedTuple
import requests
from lxml import html # type: ignore
covid_data = namedtuple("covid_data", "cases deaths recovered")
class CovidData(NamedTuple):
cases: int
deaths: int
recovered: int
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> CovidData:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
return CovidData(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}