mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 02:18:39 +00:00
Compare commits
No commits in common. "f54a9668103e560f20b50559fb54ac38a74d1fe8" and "07e68128883b84fb7e342c6bce88863a05fbbf62" have entirely different histories.
f54a966810
...
07e6812888
@ -15,8 +15,8 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: auto-walrus
|
- id: auto-walrus
|
||||||
|
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||||
rev: v0.0.274
|
rev: v0.0.272
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
|
|
||||||
|
@ -1,114 +0,0 @@
|
|||||||
"""
|
|
||||||
Conversion of energy units.
|
|
||||||
|
|
||||||
Available units: joule, kilojoule, megajoule, gigajoule,\
|
|
||||||
wattsecond, watthour, kilowatthour, newtonmeter, calorie_nutr,\
|
|
||||||
kilocalorie_nutr, electronvolt, britishthermalunit_it, footpound
|
|
||||||
|
|
||||||
USAGE :
|
|
||||||
-> Import this file into their respective project.
|
|
||||||
-> Use the function energy_conversion() for conversion of energy units.
|
|
||||||
-> Parameters :
|
|
||||||
-> from_type : From which type you want to convert
|
|
||||||
-> to_type : To which type you want to convert
|
|
||||||
-> value : the value which you want to convert
|
|
||||||
|
|
||||||
REFERENCES :
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Units_of_energy
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Joule
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Kilowatt-hour
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Newton-metre
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Calorie
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Electronvolt
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/British_thermal_unit
|
|
||||||
-> Wikipedia reference: https://en.wikipedia.org/wiki/Foot-pound_(energy)
|
|
||||||
-> Unit converter reference: https://www.unitconverters.net/energy-converter.html
|
|
||||||
"""
|
|
||||||
|
|
||||||
ENERGY_CONVERSION: dict[str, float] = {
|
|
||||||
"joule": 1.0,
|
|
||||||
"kilojoule": 1_000,
|
|
||||||
"megajoule": 1_000_000,
|
|
||||||
"gigajoule": 1_000_000_000,
|
|
||||||
"wattsecond": 1.0,
|
|
||||||
"watthour": 3_600,
|
|
||||||
"kilowatthour": 3_600_000,
|
|
||||||
"newtonmeter": 1.0,
|
|
||||||
"calorie_nutr": 4_186.8,
|
|
||||||
"kilocalorie_nutr": 4_186_800.00,
|
|
||||||
"electronvolt": 1.602_176_634e-19,
|
|
||||||
"britishthermalunit_it": 1_055.055_85,
|
|
||||||
"footpound": 1.355_818,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def energy_conversion(from_type: str, to_type: str, value: float) -> float:
|
|
||||||
"""
|
|
||||||
Conversion of energy units.
|
|
||||||
>>> energy_conversion("joule", "joule", 1)
|
|
||||||
1.0
|
|
||||||
>>> energy_conversion("joule", "kilojoule", 1)
|
|
||||||
0.001
|
|
||||||
>>> energy_conversion("joule", "megajoule", 1)
|
|
||||||
1e-06
|
|
||||||
>>> energy_conversion("joule", "gigajoule", 1)
|
|
||||||
1e-09
|
|
||||||
>>> energy_conversion("joule", "wattsecond", 1)
|
|
||||||
1.0
|
|
||||||
>>> energy_conversion("joule", "watthour", 1)
|
|
||||||
0.0002777777777777778
|
|
||||||
>>> energy_conversion("joule", "kilowatthour", 1)
|
|
||||||
2.7777777777777776e-07
|
|
||||||
>>> energy_conversion("joule", "newtonmeter", 1)
|
|
||||||
1.0
|
|
||||||
>>> energy_conversion("joule", "calorie_nutr", 1)
|
|
||||||
0.00023884589662749592
|
|
||||||
>>> energy_conversion("joule", "kilocalorie_nutr", 1)
|
|
||||||
2.388458966274959e-07
|
|
||||||
>>> energy_conversion("joule", "electronvolt", 1)
|
|
||||||
6.241509074460763e+18
|
|
||||||
>>> energy_conversion("joule", "britishthermalunit_it", 1)
|
|
||||||
0.0009478171226670134
|
|
||||||
>>> energy_conversion("joule", "footpound", 1)
|
|
||||||
0.7375621211696556
|
|
||||||
>>> energy_conversion("joule", "megajoule", 1000)
|
|
||||||
0.001
|
|
||||||
>>> energy_conversion("calorie_nutr", "kilocalorie_nutr", 1000)
|
|
||||||
1.0
|
|
||||||
>>> energy_conversion("kilowatthour", "joule", 10)
|
|
||||||
36000000.0
|
|
||||||
>>> energy_conversion("britishthermalunit_it", "footpound", 1)
|
|
||||||
778.1692306784539
|
|
||||||
>>> energy_conversion("watthour", "joule", "a") # doctest: +ELLIPSIS
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
TypeError: unsupported operand type(s) for /: 'str' and 'float'
|
|
||||||
>>> energy_conversion("wrongunit", "joule", 1) # doctest: +ELLIPSIS
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
ValueError: Incorrect 'from_type' or 'to_type' value: 'wrongunit', 'joule'
|
|
||||||
Valid values are: joule, ... footpound
|
|
||||||
>>> energy_conversion("joule", "wrongunit", 1) # doctest: +ELLIPSIS
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
ValueError: Incorrect 'from_type' or 'to_type' value: 'joule', 'wrongunit'
|
|
||||||
Valid values are: joule, ... footpound
|
|
||||||
>>> energy_conversion("123", "abc", 1) # doctest: +ELLIPSIS
|
|
||||||
Traceback (most recent call last):
|
|
||||||
...
|
|
||||||
ValueError: Incorrect 'from_type' or 'to_type' value: '123', 'abc'
|
|
||||||
Valid values are: joule, ... footpound
|
|
||||||
"""
|
|
||||||
if to_type not in ENERGY_CONVERSION or from_type not in ENERGY_CONVERSION:
|
|
||||||
msg = (
|
|
||||||
f"Incorrect 'from_type' or 'to_type' value: {from_type!r}, {to_type!r}\n"
|
|
||||||
f"Valid values are: {', '.join(ENERGY_CONVERSION)}"
|
|
||||||
)
|
|
||||||
raise ValueError(msg)
|
|
||||||
return value * ENERGY_CONVERSION[from_type] / ENERGY_CONVERSION[to_type]
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
import doctest
|
|
||||||
|
|
||||||
doctest.testmod()
|
|
@ -32,7 +32,7 @@ class Deque:
|
|||||||
the number of nodes
|
the number of nodes
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = ("_front", "_back", "_len")
|
__slots__ = ["_front", "_back", "_len"]
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class _Node:
|
class _Node:
|
||||||
@ -54,7 +54,7 @@ class Deque:
|
|||||||
the current node of the iteration.
|
the current node of the iteration.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
__slots__ = "_cur"
|
__slots__ = ["_cur"]
|
||||||
|
|
||||||
def __init__(self, cur: Deque._Node | None) -> None:
|
def __init__(self, cur: Deque._Node | None) -> None:
|
||||||
self._cur = cur
|
self._cur = cur
|
||||||
|
@ -1,89 +0,0 @@
|
|||||||
"""
|
|
||||||
This script implements the Dijkstra algorithm on a binary grid.
|
|
||||||
The grid consists of 0s and 1s, where 1 represents
|
|
||||||
a walkable node and 0 represents an obstacle.
|
|
||||||
The algorithm finds the shortest path from a start node to a destination node.
|
|
||||||
Diagonal movement can be allowed or disallowed.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from heapq import heappop, heappush
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
|
|
||||||
def dijkstra(
|
|
||||||
grid: np.ndarray,
|
|
||||||
source: tuple[int, int],
|
|
||||||
destination: tuple[int, int],
|
|
||||||
allow_diagonal: bool,
|
|
||||||
) -> tuple[float | int, list[tuple[int, int]]]:
|
|
||||||
"""
|
|
||||||
Implements Dijkstra's algorithm on a binary grid.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
grid (np.ndarray): A 2D numpy array representing the grid.
|
|
||||||
1 represents a walkable node and 0 represents an obstacle.
|
|
||||||
source (Tuple[int, int]): A tuple representing the start node.
|
|
||||||
destination (Tuple[int, int]): A tuple representing the
|
|
||||||
destination node.
|
|
||||||
allow_diagonal (bool): A boolean determining whether
|
|
||||||
diagonal movements are allowed.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Tuple[Union[float, int], List[Tuple[int, int]]]:
|
|
||||||
The shortest distance from the start node to the destination node
|
|
||||||
and the shortest path as a list of nodes.
|
|
||||||
|
|
||||||
>>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), False)
|
|
||||||
(4.0, [(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)])
|
|
||||||
|
|
||||||
>>> dijkstra(np.array([[1, 1, 1], [0, 1, 0], [0, 1, 1]]), (0, 0), (2, 2), True)
|
|
||||||
(2.0, [(0, 0), (1, 1), (2, 2)])
|
|
||||||
|
|
||||||
>>> dijkstra(np.array([[1, 1, 1], [0, 0, 1], [0, 1, 1]]), (0, 0), (2, 2), False)
|
|
||||||
(4.0, [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)])
|
|
||||||
"""
|
|
||||||
rows, cols = grid.shape
|
|
||||||
dx = [-1, 1, 0, 0]
|
|
||||||
dy = [0, 0, -1, 1]
|
|
||||||
if allow_diagonal:
|
|
||||||
dx += [-1, -1, 1, 1]
|
|
||||||
dy += [-1, 1, -1, 1]
|
|
||||||
|
|
||||||
queue, visited = [(0, source)], set()
|
|
||||||
matrix = np.full((rows, cols), np.inf)
|
|
||||||
matrix[source] = 0
|
|
||||||
predecessors = np.empty((rows, cols), dtype=object)
|
|
||||||
predecessors[source] = None
|
|
||||||
|
|
||||||
while queue:
|
|
||||||
(dist, (x, y)) = heappop(queue)
|
|
||||||
if (x, y) in visited:
|
|
||||||
continue
|
|
||||||
visited.add((x, y))
|
|
||||||
|
|
||||||
if (x, y) == destination:
|
|
||||||
path = []
|
|
||||||
while (x, y) != source:
|
|
||||||
path.append((x, y))
|
|
||||||
x, y = predecessors[x, y]
|
|
||||||
path.append(source) # add the source manually
|
|
||||||
path.reverse()
|
|
||||||
return matrix[destination], path
|
|
||||||
|
|
||||||
for i in range(len(dx)):
|
|
||||||
nx, ny = x + dx[i], y + dy[i]
|
|
||||||
if 0 <= nx < rows and 0 <= ny < cols:
|
|
||||||
next_node = grid[nx][ny]
|
|
||||||
if next_node == 1 and matrix[nx, ny] > dist + 1:
|
|
||||||
heappush(queue, (dist + 1, (nx, ny)))
|
|
||||||
matrix[nx, ny] = dist + 1
|
|
||||||
predecessors[nx, ny] = (x, y)
|
|
||||||
|
|
||||||
return np.inf, []
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
import doctest
|
|
||||||
|
|
||||||
doctest.testmod()
|
|
@ -67,7 +67,7 @@ def benchmark():
|
|||||||
|
|
||||||
|
|
||||||
class TestLeastCommonMultiple(unittest.TestCase):
|
class TestLeastCommonMultiple(unittest.TestCase):
|
||||||
test_inputs = (
|
test_inputs = [
|
||||||
(10, 20),
|
(10, 20),
|
||||||
(13, 15),
|
(13, 15),
|
||||||
(4, 31),
|
(4, 31),
|
||||||
@ -77,8 +77,8 @@ class TestLeastCommonMultiple(unittest.TestCase):
|
|||||||
(12, 25),
|
(12, 25),
|
||||||
(10, 25),
|
(10, 25),
|
||||||
(6, 9),
|
(6, 9),
|
||||||
)
|
]
|
||||||
expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18)
|
expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18]
|
||||||
|
|
||||||
def test_lcm_function(self):
|
def test_lcm_function(self):
|
||||||
for i, (first_num, second_num) in enumerate(self.test_inputs):
|
for i, (first_num, second_num) in enumerate(self.test_inputs):
|
||||||
|
@ -17,7 +17,7 @@ This script is inspired by a corresponding research paper.
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
def sigmoid(vector: np.ndarray) -> np.ndarray:
|
def sigmoid(vector: np.array) -> np.array:
|
||||||
"""
|
"""
|
||||||
Mathematical function sigmoid takes a vector x of K real numbers as input and
|
Mathematical function sigmoid takes a vector x of K real numbers as input and
|
||||||
returns 1/ (1 + e^-x).
|
returns 1/ (1 + e^-x).
|
||||||
@ -29,15 +29,17 @@ def sigmoid(vector: np.ndarray) -> np.ndarray:
|
|||||||
return 1 / (1 + np.exp(-vector))
|
return 1 / (1 + np.exp(-vector))
|
||||||
|
|
||||||
|
|
||||||
def sigmoid_linear_unit(vector: np.ndarray) -> np.ndarray:
|
def sigmoid_linear_unit(vector: np.array) -> np.array:
|
||||||
"""
|
"""
|
||||||
Implements the Sigmoid Linear Unit (SiLU) or swish function
|
Implements the Sigmoid Linear Unit (SiLU) or swish function
|
||||||
|
|
||||||
Parameters:
|
Parameters:
|
||||||
vector (np.ndarray): A numpy array consisting of real values
|
vector (np.array): A numpy array consisting of real
|
||||||
|
values.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
swish_vec (np.ndarray): The input numpy array, after applying swish
|
swish_vec (np.array): The input numpy array, after applying
|
||||||
|
swish.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
>>> sigmoid_linear_unit(np.array([-1.0, 1.0, 2.0]))
|
>>> sigmoid_linear_unit(np.array([-1.0, 1.0, 2.0]))
|
||||||
|
@ -47,18 +47,18 @@ import os
|
|||||||
|
|
||||||
class PokerHand:
|
class PokerHand:
|
||||||
"""Create an object representing a Poker Hand based on an input of a
|
"""Create an object representing a Poker Hand based on an input of a
|
||||||
string which represents the best 5-card combination from the player's hand
|
string which represents the best 5 card combination from the player's hand
|
||||||
and board cards.
|
and board cards.
|
||||||
|
|
||||||
Attributes: (read-only)
|
Attributes: (read-only)
|
||||||
hand: a string representing the hand consisting of five cards
|
hand: string representing the hand consisting of five cards
|
||||||
|
|
||||||
Methods:
|
Methods:
|
||||||
compare_with(opponent): takes in player's hand (self) and
|
compare_with(opponent): takes in player's hand (self) and
|
||||||
opponent's hand (opponent) and compares both hands according to
|
opponent's hand (opponent) and compares both hands according to
|
||||||
the rules of Texas Hold'em.
|
the rules of Texas Hold'em.
|
||||||
Returns one of 3 strings (Win, Loss, Tie) based on whether
|
Returns one of 3 strings (Win, Loss, Tie) based on whether
|
||||||
player's hand is better than the opponent's hand.
|
player's hand is better than opponent's hand.
|
||||||
|
|
||||||
hand_name(): Returns a string made up of two parts: hand name
|
hand_name(): Returns a string made up of two parts: hand name
|
||||||
and high card.
|
and high card.
|
||||||
@ -66,11 +66,11 @@ class PokerHand:
|
|||||||
Supported operators:
|
Supported operators:
|
||||||
Rich comparison operators: <, >, <=, >=, ==, !=
|
Rich comparison operators: <, >, <=, >=, ==, !=
|
||||||
|
|
||||||
Supported built-in methods and functions:
|
Supported builtin methods and functions:
|
||||||
list.sort(), sorted()
|
list.sort(), sorted()
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_HAND_NAME = (
|
_HAND_NAME = [
|
||||||
"High card",
|
"High card",
|
||||||
"One pair",
|
"One pair",
|
||||||
"Two pairs",
|
"Two pairs",
|
||||||
@ -81,10 +81,10 @@ class PokerHand:
|
|||||||
"Four of a kind",
|
"Four of a kind",
|
||||||
"Straight flush",
|
"Straight flush",
|
||||||
"Royal flush",
|
"Royal flush",
|
||||||
)
|
]
|
||||||
|
|
||||||
_CARD_NAME = (
|
_CARD_NAME = [
|
||||||
"", # placeholder as tuples are zero-indexed
|
"", # placeholder as lists are zero indexed
|
||||||
"One",
|
"One",
|
||||||
"Two",
|
"Two",
|
||||||
"Three",
|
"Three",
|
||||||
@ -99,7 +99,7 @@ class PokerHand:
|
|||||||
"Queen",
|
"Queen",
|
||||||
"King",
|
"King",
|
||||||
"Ace",
|
"Ace",
|
||||||
)
|
]
|
||||||
|
|
||||||
def __init__(self, hand: str) -> None:
|
def __init__(self, hand: str) -> None:
|
||||||
"""
|
"""
|
||||||
|
@ -103,7 +103,6 @@ max-complexity = 17 # default: 10
|
|||||||
"machine_learning/linear_discriminant_analysis.py" = ["ARG005"]
|
"machine_learning/linear_discriminant_analysis.py" = ["ARG005"]
|
||||||
"machine_learning/sequential_minimum_optimization.py" = ["SIM115"]
|
"machine_learning/sequential_minimum_optimization.py" = ["SIM115"]
|
||||||
"matrix/sherman_morrison.py" = ["SIM103", "SIM114"]
|
"matrix/sherman_morrison.py" = ["SIM103", "SIM114"]
|
||||||
"other/l*u_cache.py" = ["RUF012"]
|
|
||||||
"physics/newtons_second_law_of_motion.py" = ["BLE001"]
|
"physics/newtons_second_law_of_motion.py" = ["BLE001"]
|
||||||
"project_euler/problem_099/sol1.py" = ["SIM115"]
|
"project_euler/problem_099/sol1.py" = ["SIM115"]
|
||||||
"sorts/external_sort.py" = ["SIM115"]
|
"sorts/external_sort.py" = ["SIM115"]
|
||||||
|
Loading…
x
Reference in New Issue
Block a user