Skip to content

Numerous significant improvements Beta #12811

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 76 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
6891142
Add doctests for butterfly_pattern.py
lighting9999 Jun 28, 2025
22083ae
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
d9b07df
Update minimum_spanning_tree_kruskal2.py
lighting9999 Jun 28, 2025
97b33b2
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
158128c
Update lru_cache.py
lighting9999 Jun 28, 2025
cecabe3
Update lru_cache.py
lighting9999 Jun 28, 2025
9d16049
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
2c17e86
Update lfu_cache.py
lighting9999 Jun 28, 2025
fcadabe
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
1e71b72
Update lfu_cache.py
lighting9999 Jun 28, 2025
34da76f
Update stack_with_doubly_linked_list.py
lighting9999 Jun 28, 2025
ae755a6
Update skew_heap.py
lighting9999 Jun 28, 2025
fb07e07
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
be9ff5b
Update skew_heap.py
lighting9999 Jun 28, 2025
8abfbf1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
bd9bdf9
Update skew_heap.py
lighting9999 Jun 28, 2025
60cb936
Update skew_heap.py
lighting9999 Jun 28, 2025
3627416
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
d42704a
Update skew_heap.py
lighting9999 Jun 28, 2025
c78fbf7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 28, 2025
6e7bd44
Update skew_heap.py
lighting9999 Jun 28, 2025
24baa2b
Update test_digital_image_processing.py
lighting9999 Jun 29, 2025
127378f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
f3f0898
Update test_digital_image_processing.py
lighting9999 Jun 29, 2025
aa46117
Update test_digital_image_processing.py
lighting9999 Jun 29, 2025
fe0c1b6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
eed74bf
Update minimum_spanning_tree_prims2.py
lighting9999 Jun 29, 2025
8404a25
Update minimum_spanning_tree_prims2.py
lighting9999 Jun 29, 2025
a978c35
Update minimum_spanning_tree_prims2.py
lighting9999 Jun 29, 2025
a7e4603
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
dd16651
Update minimum_spanning_tree_prims2.py
lighting9999 Jun 29, 2025
3793d09
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
98e9282
Update matrix_class.py
lighting9999 Jun 29, 2025
54f2730
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
d5ab844
Update matrix_class.py
lighting9999 Jun 29, 2025
d1d1bcc
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
a961455
Update matrix_class.py
lighting9999 Jun 29, 2025
8eace88
Update matrix_class.py
lighting9999 Jun 29, 2025
ac0dfd3
Update matrix_class.py
lighting9999 Jun 29, 2025
b863139
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
8166650
Update skew_heap.py
lighting9999 Jun 29, 2025
5508c20
Update skew_heap.py
lighting9999 Jun 29, 2025
f157d20
Update skew_heap.py
lighting9999 Jun 29, 2025
a24fd46
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
b4117d8
Update skew_heap.py
lighting9999 Jun 29, 2025
f0beacc
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
6b07de6
Update skew_heap.py
lighting9999 Jun 29, 2025
0febfb5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
78fe5bb
Update skew_heap.py
lighting9999 Jun 29, 2025
283601d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
e013166
Update skew_heap.py
lighting9999 Jun 29, 2025
cf707b5
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
b33f0b0
Update skew_heap.py
lighting9999 Jun 29, 2025
f0a4b6a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
4f0910c
Update skew_heap.py
lighting9999 Jun 29, 2025
180d8d5
Update skew_heap.py
lighting9999 Jun 29, 2025
c5693db
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
84ec049
Update skew_heap.py
lighting9999 Jun 29, 2025
1273319
Update skew_heap.py
lighting9999 Jun 29, 2025
a1a379c
Update minimum_spanning_tree_prims2.py
lighting9999 Jun 29, 2025
bf11752
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
4226641
fix sum_of_digits.py
lighting9999 Jun 29, 2025
a2b2951
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
3361c55
Update skew_heap.py
lighting9999 Jun 29, 2025
96ade05
Update skew_heap.py
lighting9999 Jun 29, 2025
bf93372
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
072a3d6
fix skew_heap.py
lighting9999 Jun 29, 2025
ed6be0a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
a35036f
fix l001 skew_heap.py
lighting9999 Jun 29, 2025
208adb1
Update skew_heap.py
lighting9999 Jun 29, 2025
06cb5d3
Update atbash.py
lighting9999 Jun 29, 2025
b1e0e3f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
23772e7
Update pascal_triangle.py
lighting9999 Jun 29, 2025
adc0210
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
13d179b
Update pascal_triangle.py
lighting9999 Jun 29, 2025
21e2c45
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Jun 29, 2025
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
64 changes: 23 additions & 41 deletions ciphers/atbash.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,52 +3,34 @@
import string


def atbash_slow(sequence: str) -> str:
def atbash(text: str) -> str:
"""
>>> atbash_slow("ABCDEFG")
'ZYXWVUT'
Encodes or decodes text using the Atbash cipher.

>>> atbash_slow("aW;;123BX")
'zD;;123YC'
"""
output = ""
for i in sequence:
extract = ord(i)
if 65 <= extract <= 90:
output += chr(155 - extract)
elif 97 <= extract <= 122:
output += chr(219 - extract)
else:
output += i
return output


def atbash(sequence: str) -> str:
"""
>>> atbash("ABCDEFG")
'ZYXWVUT'

>>> atbash("aW;;123BX")
'zD;;123YC'
"""
letters = string.ascii_letters
letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(c)] if c in letters else c for c in sequence
)
The Atbash cipher substitutes each letter with its mirror in the alphabet:
A -> Z, B -> Y, C -> X, ... Z -> A (case is preserved)
Non-alphabetic characters are left unchanged.

Args:
text: The input string to encode/decode

def benchmark() -> None:
"""Let's benchmark our functions side-by-side..."""
from timeit import timeit
Returns:
The transformed string
"""
# Create translation tables for uppercase and lowercase
lowercase_map = str.maketrans(string.ascii_lowercase, string.ascii_lowercase[::-1])
uppercase_map = str.maketrans(string.ascii_uppercase, string.ascii_uppercase[::-1])

print("Running performance benchmarks...")
setup = "from string import printable ; from __main__ import atbash, atbash_slow"
print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds")
print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds")
# Apply both translation mappings
return text.translate(lowercase_map).translate(uppercase_map)


# Example usage
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f"{example} encrypted in atbash: {atbash(example)}")
benchmark()
test_string = "Hello, World! 123"
encoded = atbash(test_string)
decoded = atbash(encoded)

print(f"Original: {test_string}")
print(f"Encoded: {encoded}")
print(f"Decoded: {decoded}")
146 changes: 73 additions & 73 deletions data_structures/heap/skew_heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,23 @@

from __future__ import annotations

from collections.abc import Iterable, Iterator
from typing import Any, Generic, TypeVar
from collections.abc import Callable, Iterable, Iterator
from typing import Any

T = TypeVar("T", bound=bool)


class SkewNode(Generic[T]):
class SkewNode:
"""
One node of the skew heap. Contains the value and references to
two children.
"""

def __init__(self, value: T) -> None:
self._value: T = value
self.left: SkewNode[T] | None = None
self.right: SkewNode[T] | None = None
def __init__(self, value: Any) -> None:
self._value: Any = value
self.left: SkewNode | None = None
self.right: SkewNode | None = None

@property
def value(self) -> T:
def value(self) -> Any:
"""
Return the value of the node.

Expand All @@ -30,68 +28,56 @@ def value(self) -> T:
3.14159
>>> SkewNode("hello").value
'hello'
>>> SkewNode(None).value

>>> SkewNode(True).value
True
>>> SkewNode([]).value
[]
>>> SkewNode({}).value
{}
>>> SkewNode(set()).value
set()
>>> SkewNode(0.0).value
0.0
>>> SkewNode(-1e-10).value
-1e-10
>>> SkewNode(10).value
10
>>> SkewNode(-10.5).value
-10.5
>>> SkewNode().value
Traceback (most recent call last):
...
TypeError: SkewNode.__init__() missing 1 required positional argument: 'value'
"""
return self._value

@staticmethod
def merge(
root1: SkewNode[T] | None, root2: SkewNode[T] | None
) -> SkewNode[T] | None:
root1: SkewNode | None, root2: SkewNode | None, comp: Callable[[Any, Any], bool]
) -> SkewNode | None:
"""
Merge 2 nodes together.
>>> SkewNode.merge(SkewNode(10),SkewNode(-10.5)).value
Merge two nodes together.
>>> def comp(a, b): return a < b
>>> SkewNode.merge(SkewNode(10), SkewNode(-10.5), comp).value
-10.5
>>> SkewNode.merge(SkewNode(10),SkewNode(10.5)).value
>>> SkewNode.merge(SkewNode(10), SkewNode(10.5), comp).value
10
>>> SkewNode.merge(SkewNode(10),SkewNode(10)).value
>>> SkewNode.merge(SkewNode(10), SkewNode(10), comp).value
10
>>> SkewNode.merge(SkewNode(-100),SkewNode(-10.5)).value
>>> SkewNode.merge(SkewNode(-100), SkewNode(-10.5), comp).value
-100
"""
# Handle empty nodes
if not root1:
return root2

if not root2:
return root1

if root1.value > root2.value:
root1, root2 = root2, root1

result = root1
temp = root1.right
result.right = root1.left
result.left = SkewNode.merge(temp, root2)

return result


class SkewHeap(Generic[T]):
# Compare values using provided comparison function
if comp(root1.value, root2.value):
# root1 is smaller, make it the new root
result = root1
temp = root1.right
result.right = root1.left
result.left = SkewNode.merge(temp, root2, comp)
return result
else:
# root2 is smaller or equal, use it as new root
result = root2
temp = root2.right
result.right = root2.left
result.left = SkewNode.merge(root1, temp, comp)
return result


class SkewHeap:
"""
A data structure that allows inserting a new value and to pop the smallest
values. Both operations take O(logN) time where N is the size of the
structure.
A data structure that allows inserting a new value and popping the smallest
values. Both operations take O(logN) time where N is the size of the heap.
Wiki: https://en.wikipedia.org/wiki/Skew_heap
Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html

Expand All @@ -111,20 +97,32 @@ class SkewHeap(Generic[T]):
[-1, 0, 1]
"""

def __init__(self, data: Iterable[T] | None = ()) -> None:
def __init__(
self,
data: Iterable[Any] | None = None,
comp: Callable[[Any, Any], bool] = lambda a, b: a < b,
) -> None:
"""
Initialize the skew heap with optional data and comparison function

>>> sh = SkewHeap([3, 1, 3, 7])
>>> list(sh)
[1, 3, 3, 7]

# Max-heap example
>>> max_heap = SkewHeap([3, 1, 3, 7], comp=lambda a, b: a > b)
>>> list(max_heap)
[7, 3, 3, 1]
"""
self._root: SkewNode[T] | None = None
self._root: SkewNode | None = None
self._comp = comp
if data:
for item in data:
self.insert(item)

def __bool__(self) -> bool:
"""
Check if the heap is not empty.
Check if the heap is not empty

>>> sh = SkewHeap()
>>> bool(sh)
Expand All @@ -138,27 +136,31 @@ def __bool__(self) -> bool:
"""
return self._root is not None

def __iter__(self) -> Iterator[T]:
def __iter__(self) -> Iterator[Any]:
"""
Returns sorted list containing all the values in the heap.
Iterate through all values in sorted order

>>> sh = SkewHeap([3, 1, 3, 7])
>>> list(sh)
[1, 3, 3, 7]
"""
# Create a temporary heap for iteration
temp_heap = SkewHeap(comp=self._comp)
result: list[Any] = []
while self:
result.append(self.pop())

# Pushing items back to the heap not to clear it.
for item in result:
self.insert(item)
# Pop all elements from the heap
while self:
item = self.pop()
result.append(item)
temp_heap.insert(item)

# Restore the heap state
self._root = temp_heap._root
return iter(result)

def insert(self, value: T) -> None:
def insert(self, value: Any) -> None:
"""
Insert the value into the heap.
Insert a new value into the heap

>>> sh = SkewHeap()
>>> sh.insert(3)
Expand All @@ -168,11 +170,11 @@ def insert(self, value: T) -> None:
>>> list(sh)
[1, 3, 3, 7]
"""
self._root = SkewNode.merge(self._root, SkewNode(value))
self._root = SkewNode.merge(self._root, SkewNode(value), self._comp)

def pop(self) -> T | None:
def pop(self) -> Any:
"""
Pop the smallest value from the heap and return it.
Remove and return the smallest value from the heap

>>> sh = SkewHeap([3, 1, 3, 7])
>>> sh.pop()
Expand All @@ -189,15 +191,13 @@ def pop(self) -> T | None:
IndexError: Can't get top element for the empty heap.
"""
result = self.top()
self._root = (
SkewNode.merge(self._root.left, self._root.right) if self._root else None
)

if self._root:
self._root = SkewNode.merge(self._root.left, self._root.right, self._comp)
return result

def top(self) -> T:
def top(self) -> Any:
"""
Return the smallest value from the heap.
Return the smallest value without removing it

>>> sh = SkewHeap()
>>> sh.insert(3)
Expand All @@ -219,7 +219,7 @@ def top(self) -> T:

def clear(self) -> None:
"""
Clear the heap.
Clear all elements from the heap

>>> sh = SkewHeap([3, 1, 3, 7])
>>> sh.clear()
Expand Down
8 changes: 2 additions & 6 deletions data_structures/stacks/stack_with_doubly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,15 @@

from __future__ import annotations

from typing import Generic, TypeVar

T = TypeVar("T")


class Node(Generic[T]):
class Node[T]:
def __init__(self, data: T):
self.data = data # Assign data
self.next: Node[T] | None = None # Initialize next as null
self.prev: Node[T] | None = None # Initialize prev as null


class Stack(Generic[T]):
class Stack[T]:
"""
>>> stack = Stack()
>>> stack.is_empty()
Expand Down
Loading
Loading