From ae0fc85401efd9816193a06e554a66600cc09a97 Mon Sep 17 00:00:00 2001 From: Tianyi Zheng Date: Wed, 9 Aug 2023 00:55:30 -0700 Subject: [PATCH] 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> --- DIRECTORY.md | 1 - conversions/length_conversion.py | 30 +++++++++----- conversions/pressure_conversions.py | 28 ++++++++----- conversions/volume_conversions.py | 40 +++++++++++-------- .../binary_tree/distribute_coins.py | 10 +++-- electronics/electric_power.py | 22 +++++----- graphs/bi_directional_dijkstra.py | 4 +- maths/area_under_curve.py | 6 +-- maths/decimal_to_fraction.py | 2 +- maths/line_length.py | 6 +-- maths/numerical_integration.py | 6 +-- .../single_indeterminate_operations.py | 4 +- maths/series/geometric_series.py | 10 ++--- maths/series/p_series.py | 2 +- maths/volume.py | 2 +- matrix/matrix_class.py | 4 +- matrix/matrix_operation.py | 6 +-- matrix/searching_in_sorted_matrix.py | 4 +- matrix/sherman_morrison.py | 16 ++++---- ...t_data.py => input_data.py.DEPRECATED.txt} | 0 web_programming/covid_stats_via_xpath.py | 12 ++++-- 21 files changed, 121 insertions(+), 94 deletions(-) rename neural_network/{input_data.py => input_data.py.DEPRECATED.txt} (100%) diff --git a/DIRECTORY.md b/DIRECTORY.md index e6a1ff356..5578c1c9a 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -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) diff --git a/conversions/length_conversion.py b/conversions/length_conversion.py index d8f395152..07fa93a19 100644 --- a/conversions/length_conversion.py +++ b/conversions/length_conversion.py @@ -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__": diff --git a/conversions/pressure_conversions.py b/conversions/pressure_conversions.py index e0cd18d23..fe78b1382 100644 --- a/conversions/pressure_conversions.py +++ b/conversions/pressure_conversions.py @@ -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 ) diff --git a/conversions/volume_conversions.py b/conversions/volume_conversions.py index 44d290091..cb2403805 100644 --- a/conversions/volume_conversions.py +++ b/conversions/volume_conversions.py @@ -18,35 +18,39 @@ 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), } 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 @@ -54,7 +58,7 @@ def volume_conversion(value: float, from_type: str, to_type: str) -> float: 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( @@ -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__": diff --git a/data_structures/binary_tree/distribute_coins.py b/data_structures/binary_tree/distribute_coins.py index ea02afc2c..5712604cb 100644 --- a/data_structures/binary_tree/distribute_coins.py +++ b/data_structures/binary_tree/distribute_coins.py @@ -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: diff --git a/electronics/electric_power.py b/electronics/electric_power.py index e59795601..8b92e320a 100644 --- a/electronics/electric_power.py +++ b/electronics/electric_power.py @@ -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") diff --git a/graphs/bi_directional_dijkstra.py b/graphs/bi_directional_dijkstra.py index a4489026b..529a235db 100644 --- a/graphs/bi_directional_dijkstra.py +++ b/graphs/bi_directional_dijkstra.py @@ -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 diff --git a/maths/area_under_curve.py b/maths/area_under_curve.py index b557b2029..0da6546b2 100644 --- a/maths/area_under_curve.py +++ b/maths/area_under_curve.py @@ -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: """ diff --git a/maths/decimal_to_fraction.py b/maths/decimal_to_fraction.py index 9462bafe0..2aa8e3c3d 100644 --- a/maths/decimal_to_fraction.py +++ b/maths/decimal_to_fraction.py @@ -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) diff --git a/maths/line_length.py b/maths/line_length.py index b810f2d9a..ed2efc31e 100644 --- a/maths/line_length.py +++ b/maths/line_length.py @@ -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: """ diff --git a/maths/numerical_integration.py b/maths/numerical_integration.py index f2d65f89e..4ac562644 100644 --- a/maths/numerical_integration.py +++ b/maths/numerical_integration.py @@ -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: """ diff --git a/maths/polynomials/single_indeterminate_operations.py b/maths/polynomials/single_indeterminate_operations.py index 8bafdb591..e31e6caa3 100644 --- a/maths/polynomials/single_indeterminate_operations.py +++ b/maths/polynomials/single_indeterminate_operations.py @@ -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]) diff --git a/maths/series/geometric_series.py b/maths/series/geometric_series.py index 90c9fe77b..b8d6a8620 100644 --- a/maths/series/geometric_series.py +++ b/maths/series/geometric_series.py @@ -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)): diff --git a/maths/series/p_series.py b/maths/series/p_series.py index 34fa3f239..a091a6f3f 100644 --- a/maths/series/p_series.py +++ b/maths/series/p_series.py @@ -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 diff --git a/maths/volume.py b/maths/volume.py index 1da4584c8..721974e68 100644 --- a/maths/volume.py +++ b/maths/volume.py @@ -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) diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92a..a5940a38e 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -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] diff --git a/matrix/matrix_operation.py b/matrix/matrix_operation.py index f189f1898..d63e758f1 100644 --- a/matrix/matrix_operation.py +++ b/matrix/matrix_operation.py @@ -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") diff --git a/matrix/searching_in_sorted_matrix.py b/matrix/searching_in_sorted_matrix.py index ddca3b1ce..f55cc71d6 100644 --- a/matrix/searching_in_sorted_matrix.py +++ b/matrix/searching_in_sorted_matrix.py @@ -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) diff --git a/matrix/sherman_morrison.py b/matrix/sherman_morrison.py index 256271e8a..b6e50f70f 100644 --- a/matrix/sherman_morrison.py +++ b/matrix/sherman_morrison.py @@ -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: """ 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: """ 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)) diff --git a/neural_network/input_data.py b/neural_network/input_data.py.DEPRECATED.txt similarity index 100% rename from neural_network/input_data.py rename to neural_network/input_data.py.DEPRECATED.txt diff --git a/web_programming/covid_stats_via_xpath.py b/web_programming/covid_stats_via_xpath.py index 85ea5d940..a95130bad 100644 --- a/web_programming/covid_stats_via_xpath.py +++ b/web_programming/covid_stats_via_xpath.py @@ -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: {}