mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-20 00:02:04 +00:00
Compare commits
15 Commits
b22fa68a53
...
bb15cc149f
Author | SHA1 | Date | |
---|---|---|---|
|
bb15cc149f | ||
|
6c92c5a539 | ||
|
13e4d3e76c | ||
|
c666db3729 | ||
|
9fb51b4169 | ||
|
1f74db0c06 | ||
|
91ebea1d99 | ||
|
533767ff46 | ||
|
78929f65f5 | ||
|
31b48187c6 | ||
|
873dcf0c26 | ||
|
c8117dca6b | ||
|
9bd3c3f998 | ||
|
c5ba7fbee6 | ||
|
9fb47fa962 |
2
.github/workflows/sphinx.yml
vendored
2
.github/workflows/sphinx.yml
vendored
|
@ -23,7 +23,7 @@ concurrency:
|
|||
|
||||
jobs:
|
||||
build_docs:
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04-arm
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
|
|
|
@ -16,13 +16,13 @@ repos:
|
|||
- id: auto-walrus
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.9.1
|
||||
rev: v0.9.3
|
||||
hooks:
|
||||
- id: ruff
|
||||
- id: ruff-format
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
rev: v2.4.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
additional_dependencies:
|
||||
|
|
|
@ -377,6 +377,7 @@
|
|||
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
|
||||
* [Longest Common Substring](dynamic_programming/longest_common_substring.py)
|
||||
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
|
||||
* [Longest Increasing Subsequence Iterative](dynamic_programming/longest_increasing_subsequence_iterative.py)
|
||||
* [Longest Increasing Subsequence O Nlogn](dynamic_programming/longest_increasing_subsequence_o_nlogn.py)
|
||||
* [Longest Palindromic Subsequence](dynamic_programming/longest_palindromic_subsequence.py)
|
||||
* [Matrix Chain Multiplication](dynamic_programming/matrix_chain_multiplication.py)
|
||||
|
@ -424,6 +425,7 @@
|
|||
* [Resistor Color Code](electronics/resistor_color_code.py)
|
||||
* [Resistor Equivalence](electronics/resistor_equivalence.py)
|
||||
* [Resonant Frequency](electronics/resonant_frequency.py)
|
||||
* [Star Delta Transform](electronics/star_delta_transform.py)
|
||||
* [Wheatstone Bridge](electronics/wheatstone_bridge.py)
|
||||
|
||||
## File Transfer
|
||||
|
@ -462,6 +464,7 @@
|
|||
|
||||
## Graphics
|
||||
* [Bezier Curve](graphics/bezier_curve.py)
|
||||
* [Butterfly Pattern](graphics/butterfly_pattern.py)
|
||||
* [Digital Differential Analyzer Line](graphics/digital_differential_analyzer_line.py)
|
||||
* [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py)
|
||||
|
||||
|
|
|
@ -88,7 +88,7 @@ def __prepare(
|
|||
...
|
||||
KeyError: 'Length of alphabet has to be 27.'
|
||||
|
||||
Testing with punctuations that are not in the given alphabet
|
||||
Testing with punctuation not in the given alphabet
|
||||
|
||||
>>> __prepare('am i a boy?','abCdeFghijkLmnopqrStuVwxYZ+')
|
||||
Traceback (most recent call last):
|
||||
|
@ -128,7 +128,7 @@ def encrypt_message(
|
|||
encrypt_message
|
||||
===============
|
||||
|
||||
Encrypts a message using the trifid_cipher. Any punctuatuions that
|
||||
Encrypts a message using the trifid_cipher. Any punctuatuion chars that
|
||||
would be used should be added to the alphabet.
|
||||
|
||||
PARAMETERS
|
||||
|
|
|
@ -9,7 +9,9 @@ import time
|
|||
|
||||
|
||||
def cross(items_a, items_b):
|
||||
"Cross product of elements in A and elements in B."
|
||||
"""
|
||||
Cross product of elements in A and elements in B.
|
||||
"""
|
||||
return [a + b for a in items_a for b in items_b]
|
||||
|
||||
|
||||
|
@ -27,7 +29,7 @@ peers = {s: {x for u in units[s] for x in u} - {s} for s in squares}
|
|||
|
||||
|
||||
def test():
|
||||
"A set of unit tests."
|
||||
"""A set of unit tests."""
|
||||
assert len(squares) == 81
|
||||
assert len(unitlist) == 27
|
||||
assert all(len(units[s]) == 3 for s in squares)
|
||||
|
@ -47,8 +49,10 @@ def test():
|
|||
|
||||
|
||||
def parse_grid(grid):
|
||||
"""Convert grid to a dict of possible values, {square: digits}, or
|
||||
return False if a contradiction is detected."""
|
||||
"""
|
||||
Convert grid to a dict of possible values, {square: digits}, or
|
||||
return False if a contradiction is detected.
|
||||
"""
|
||||
## To start, every square can be any digit; then assign values from the grid.
|
||||
values = {s: digits for s in squares}
|
||||
for s, d in grid_values(grid).items():
|
||||
|
@ -58,15 +62,19 @@ def parse_grid(grid):
|
|||
|
||||
|
||||
def grid_values(grid):
|
||||
"Convert grid into a dict of {square: char} with '0' or '.' for empties."
|
||||
"""
|
||||
Convert grid into a dict of {square: char} with '0' or '.' for empties.
|
||||
"""
|
||||
chars = [c for c in grid if c in digits or c in "0."]
|
||||
assert len(chars) == 81
|
||||
return dict(zip(squares, chars))
|
||||
|
||||
|
||||
def assign(values, s, d):
|
||||
"""Eliminate all the other values (except d) from values[s] and propagate.
|
||||
Return values, except return False if a contradiction is detected."""
|
||||
"""
|
||||
Eliminate all the other values (except d) from values[s] and propagate.
|
||||
Return values, except return False if a contradiction is detected.
|
||||
"""
|
||||
other_values = values[s].replace(d, "")
|
||||
if all(eliminate(values, s, d2) for d2 in other_values):
|
||||
return values
|
||||
|
@ -75,8 +83,10 @@ def assign(values, s, d):
|
|||
|
||||
|
||||
def eliminate(values, s, d):
|
||||
"""Eliminate d from values[s]; propagate when values or places <= 2.
|
||||
Return values, except return False if a contradiction is detected."""
|
||||
"""
|
||||
Eliminate d from values[s]; propagate when values or places <= 2.
|
||||
Return values, except return False if a contradiction is detected.
|
||||
"""
|
||||
if d not in values[s]:
|
||||
return values ## Already eliminated
|
||||
values[s] = values[s].replace(d, "")
|
||||
|
@ -99,7 +109,9 @@ def eliminate(values, s, d):
|
|||
|
||||
|
||||
def display(values):
|
||||
"Display these values as a 2-D grid."
|
||||
"""
|
||||
Display these values as a 2-D grid.
|
||||
"""
|
||||
width = 1 + max(len(values[s]) for s in squares)
|
||||
line = "+".join(["-" * (width * 3)] * 3)
|
||||
for r in rows:
|
||||
|
@ -114,11 +126,14 @@ def display(values):
|
|||
|
||||
|
||||
def solve(grid):
|
||||
"""
|
||||
Solve the grid.
|
||||
"""
|
||||
return search(parse_grid(grid))
|
||||
|
||||
|
||||
def some(seq):
|
||||
"Return some element of seq that is true."
|
||||
"""Return some element of seq that is true."""
|
||||
for e in seq:
|
||||
if e:
|
||||
return e
|
||||
|
@ -126,7 +141,9 @@ def some(seq):
|
|||
|
||||
|
||||
def search(values):
|
||||
"Using depth-first search and propagation, try all possible values."
|
||||
"""
|
||||
Using depth-first search and propagation, try all possible values.
|
||||
"""
|
||||
if values is False:
|
||||
return False ## Failed earlier
|
||||
if all(len(values[s]) == 1 for s in squares):
|
||||
|
@ -137,9 +154,11 @@ def search(values):
|
|||
|
||||
|
||||
def solve_all(grids, name="", showif=0.0):
|
||||
"""Attempt to solve a sequence of grids. Report results.
|
||||
"""
|
||||
Attempt to solve a sequence of grids. Report results.
|
||||
When showif is a number of seconds, display puzzles that take longer.
|
||||
When showif is None, don't display any puzzles."""
|
||||
When showif is None, don't display any puzzles.
|
||||
"""
|
||||
|
||||
def time_solve(grid):
|
||||
start = time.monotonic()
|
||||
|
@ -162,7 +181,9 @@ def solve_all(grids, name="", showif=0.0):
|
|||
|
||||
|
||||
def solved(values):
|
||||
"A puzzle is solved if each unit is a permutation of the digits 1 to 9."
|
||||
"""
|
||||
A puzzle is solved if each unit is a permutation of the digits 1 to 9.
|
||||
"""
|
||||
|
||||
def unitsolved(unit):
|
||||
return {values[s] for s in unit} == set(digits)
|
||||
|
@ -177,9 +198,11 @@ def from_file(filename, sep="\n"):
|
|||
|
||||
|
||||
def random_puzzle(assignments=17):
|
||||
"""Make a random puzzle with N or more assignments. Restart on contradictions.
|
||||
"""
|
||||
Make a random puzzle with N or more assignments. Restart on contradictions.
|
||||
Note the resulting puzzle is not guaranteed to be solvable, but empirically
|
||||
about 99.8% of them are solvable. Some have multiple solutions."""
|
||||
about 99.8% of them are solvable. Some have multiple solutions.
|
||||
"""
|
||||
values = {s: digits for s in squares}
|
||||
for s in shuffled(squares):
|
||||
if not assign(values, s, random.choice(values[s])):
|
||||
|
@ -191,7 +214,9 @@ def random_puzzle(assignments=17):
|
|||
|
||||
|
||||
def shuffled(seq):
|
||||
"Return a randomly shuffled copy of the input sequence."
|
||||
"""
|
||||
Return a randomly shuffled copy of the input sequence.
|
||||
"""
|
||||
seq = list(seq)
|
||||
random.shuffle(seq)
|
||||
return seq
|
||||
|
|
|
@ -221,6 +221,10 @@ def del_node(root: MyNode, data: Any) -> MyNode | None:
|
|||
else:
|
||||
root.set_right(del_node(right_child, data))
|
||||
|
||||
# Re-fetch left_child and right_child references
|
||||
left_child = root.get_left()
|
||||
right_child = root.get_right()
|
||||
|
||||
if get_height(right_child) - get_height(left_child) == 2:
|
||||
assert right_child is not None
|
||||
if get_height(right_child.get_right()) > get_height(right_child.get_left()):
|
||||
|
|
125
electronics/star_delta_transform.py
Normal file
125
electronics/star_delta_transform.py
Normal file
|
@ -0,0 +1,125 @@
|
|||
"""
|
||||
In electrical engineering, the Y-Δ transform, also written wye-delta and also known by
|
||||
many other names, is a mathematical technique to simplify the analysis of an electrical
|
||||
network.
|
||||
The name derives from the shapes of the circuit diagrams, which look respectively like
|
||||
the letter Y and the Greek capital letter Δ. This circuit transformation theory was
|
||||
published by Arthur Edwin Kennelly in 1899. It is widely used in analysis of three-phase
|
||||
electric power circuits.
|
||||
|
||||
The Y-Δ transform can be considered a special case of the star-mesh transform for three
|
||||
resistors. In mathematics, the Y-Δ transform plays an important role in theory of
|
||||
circular planar graphs.
|
||||
|
||||
Source: https://en.wikipedia.org/wiki/Y-%CE%94_transform
|
||||
"""
|
||||
|
||||
from sys import exit
|
||||
from unittest import mock
|
||||
|
||||
|
||||
def delta_to_wye(resistors: list) -> dict:
|
||||
"""
|
||||
>>> delta_to_wye([2.0, 3.0, 4.0])
|
||||
{'r1': 1.3333333333333333, 'r2': 0.8888888888888888, 'r3': 0.6666666666666666}
|
||||
"""
|
||||
r_wye: dict = {}
|
||||
ra, rb, rc = resistors[0], resistors[1], resistors[2]
|
||||
r_wye.update({"r1": rb * rc / (ra + rb + rc)})
|
||||
r_wye.update({"r2": ra * rc / (ra + rb + rc)})
|
||||
r_wye.update({"r3": ra * rb / (ra + rb + rc)})
|
||||
return r_wye
|
||||
|
||||
|
||||
def wye_to_delta(resistors: list) -> dict:
|
||||
"""
|
||||
>>> wye_to_delta([2.0, 3.0, 4.0])
|
||||
{'ra': 13.0, 'rb': 8.666666666666666, 'rc': 6.5}
|
||||
"""
|
||||
r1, r2, r3 = resistors[0], resistors[1], resistors[2]
|
||||
r_delta: dict = {}
|
||||
r_delta.update({"ra": (r1 * r2 + r2 * r3 + r3 * r1) / r1})
|
||||
r_delta.update({"rb": (r1 * r2 + r2 * r3 + r3 * r1) / r2})
|
||||
r_delta.update({"rc": (r1 * r2 + r2 * r3 + r3 * r1) / r3})
|
||||
return r_delta
|
||||
|
||||
|
||||
def transform(mode: int, resistors: list) -> dict:
|
||||
"""
|
||||
>>> transform(1, [4.0, 5.0, 6.0])
|
||||
{'r1': 2.0, 'r2': 1.6, 'r3': 1.3333333333333333}
|
||||
|
||||
>>> transform(2, [4.0, 5.0, 6.0])
|
||||
{'ra': 18.5, 'rb': 14.8, 'rc': 12.333333333333334}
|
||||
"""
|
||||
r_transformed = {}
|
||||
if mode == 1:
|
||||
r_transformed = delta_to_wye(resistors)
|
||||
elif mode == 2:
|
||||
r_transformed = wye_to_delta(resistors)
|
||||
return r_transformed
|
||||
|
||||
|
||||
def get_type_transform() -> int:
|
||||
mode: int = 0
|
||||
try:
|
||||
print("""
|
||||
1. From delta to wye
|
||||
2. From wye to delta
|
||||
""")
|
||||
mode = int(input("? --> "))
|
||||
except ValueError:
|
||||
print("Invalid Value. Only int inputs are accepted")
|
||||
exit()
|
||||
return mode
|
||||
|
||||
|
||||
def get_resistors_values(mode: int) -> list:
|
||||
r: list = []
|
||||
print("Select conversion (type 1 or 2)")
|
||||
try:
|
||||
if mode == 1:
|
||||
r = list(
|
||||
map(
|
||||
float, input("Resistant values (format ra rb rc): ").strip().split()
|
||||
)
|
||||
)[:3]
|
||||
elif mode == 2:
|
||||
r = list(
|
||||
map(
|
||||
float, input("Resistant values (format r1 r2 r3): ").strip().split()
|
||||
)
|
||||
)[:3]
|
||||
else:
|
||||
print("Incorrect selected option. Valid option 1 or 2")
|
||||
except ValueError:
|
||||
print("Invalid Value. Only int inputs are accepted")
|
||||
exit()
|
||||
return r
|
||||
|
||||
|
||||
def test_get_type_transformation() -> None:
|
||||
with mock.patch("builtins.input", return_value="1"):
|
||||
m = get_type_transform()
|
||||
assert m == 1
|
||||
|
||||
|
||||
def test_get_resistors_values() -> None:
|
||||
with mock.patch("builtins.input", return_value="2 4 8"):
|
||||
r = get_resistors_values(2)
|
||||
assert r == [2.0, 4.0, 8.0]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
print("star - delta transform")
|
||||
mode = get_type_transform()
|
||||
r = get_resistors_values(mode)
|
||||
r_transformed = transform(mode, r)
|
||||
print(f"Result: '{r_transformed}'")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from doctest import testmod
|
||||
|
||||
testmod()
|
||||
main()
|
|
@ -46,7 +46,7 @@ def get_week_day(year: int, month: int, day: int) -> str:
|
|||
) % 7
|
||||
day_anchor = (
|
||||
DOOMSDAY_NOT_LEAP[month - 1]
|
||||
if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0)
|
||||
if year % 4 != 0 or (centurian == 0 and year % 400 != 0)
|
||||
else DOOMSDAY_LEAP[month - 1]
|
||||
)
|
||||
week_day = (dooms_day + day - day_anchor) % 7
|
||||
|
|
|
@ -159,7 +159,7 @@ lint.pylint.max-returns = 8 # default: 6
|
|||
lint.pylint.max-statements = 88 # default: 50
|
||||
|
||||
[tool.codespell]
|
||||
ignore-words-list = "3rt,ans,bitap,crate,damon,fo,followings,hist,iff,kwanza,manuel,mater,secant,som,sur,tim,toi,zar"
|
||||
ignore-words-list = "3rt,abd,aer,ans,bitap,crate,damon,fo,followings,hist,iff,kwanza,manuel,mater,secant,som,sur,tim,toi,zar"
|
||||
skip = "./.*,*.json,*.lock,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_names.txt,pyproject.toml,strings/dictionary.txt,strings/words.txt"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
|
|
|
@ -85,6 +85,8 @@ def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
|
|||
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
|
||||
>>> bubble_sort_recursive([1, 3.3, 5, 7.7, 2, 4.4, 6])
|
||||
[1, 2, 3.3, 4.4, 5, 6, 7.7]
|
||||
>>> bubble_sort_recursive(['a', 'Z', 'B', 'C', 'A', 'c'])
|
||||
['A', 'B', 'C', 'Z', 'a', 'c']
|
||||
>>> import random
|
||||
>>> collection_arg = random.sample(range(-50, 50), 100)
|
||||
>>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
|
||||
|
|
Loading…
Reference in New Issue
Block a user