repo stringlengths 7 90 | file_url stringlengths 81 315 | file_path stringlengths 4 228 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:38:15 2026-01-05 02:33:18 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/hashing/tests/__init__.py | data_structures/hashing/tests/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/hashing/number_theory/prime_numbers.py | data_structures/hashing/number_theory/prime_numbers.py | #!/usr/bin/env python3
"""
module to operations with prime numbers
"""
import math
def is_prime(number: int) -> bool:
"""Checks to see if a number is a prime in O(sqrt(n)).
A number is prime if it has exactly two factors: 1 and itself.
>>> is_prime(0)
False
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(27)
False
>>> is_prime(87)
False
>>> is_prime(563)
True
>>> is_prime(2999)
True
>>> is_prime(67483)
False
"""
# precondition
assert isinstance(number, int) and (number >= 0), (
"'number' must been an int and positive"
)
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
return not any(not number % i for i in odd_numbers)
def next_prime(value, factor=1, **kwargs):
value = factor * value
first_value_val = value
while not is_prime(value):
value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **kwargs)
return value
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/hashing/number_theory/__init__.py | data_structures/hashing/number_theory/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/singly_linked_list.py | data_structures/linked_list/singly_linked_list.py | from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
@dataclass
class Node:
"""
Create and initialize Node class instance.
>>> Node(20)
Node(20)
>>> Node("Hello, world!")
Node(Hello, world!)
>>> Node(None)
Node(None)
>>> Node(True)
Node(True)
"""
data: Any
next_node: Node | None = None
def __repr__(self) -> str:
"""
Get the string representation of this node.
>>> Node(10).__repr__()
'Node(10)'
>>> repr(Node(10))
'Node(10)'
>>> str(Node(10))
'Node(10)'
>>> Node(10)
Node(10)
"""
return f"Node({self.data})"
class LinkedList:
def __init__(self):
"""
Create and initialize LinkedList class instance.
>>> linked_list = LinkedList()
>>> linked_list.head is None
True
"""
self.head = None
def __iter__(self) -> Iterator[Any]:
"""
This function is intended for iterators to access
and iterate through data inside linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list.insert_tail("tail_1")
>>> linked_list.insert_tail("tail_2")
>>> for node in linked_list: # __iter__ used here.
... node
'tail'
'tail_1'
'tail_2'
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
Return length of linked list i.e. number of nodes
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.insert_tail("tail")
>>> len(linked_list)
1
>>> linked_list.insert_head("head")
>>> len(linked_list)
2
>>> _ = linked_list.delete_tail()
>>> len(linked_list)
1
>>> _ = linked_list.delete_head()
>>> len(linked_list)
0
"""
return sum(1 for _ in self)
def __repr__(self) -> str:
"""
String representation/visualization of a Linked Lists
>>> linked_list = LinkedList()
>>> linked_list.insert_tail(1)
>>> linked_list.insert_tail(3)
>>> linked_list.__repr__()
'1 -> 3'
>>> repr(linked_list)
'1 -> 3'
>>> str(linked_list)
'1 -> 3'
>>> linked_list.insert_tail(5)
>>> f"{linked_list}"
'1 -> 3 -> 5'
"""
return " -> ".join([str(item) for item in self])
def __getitem__(self, index: int) -> Any:
"""
Indexing Support. Used to get a node at particular position
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
True
>>> linked_list[-10]
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)]
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
for i, node in enumerate(self):
if i == index:
return node
return None
# Used to change the data of a particular node
def __setitem__(self, index: int, data: Any) -> None:
"""
>>> linked_list = LinkedList()
>>> for i in range(0, 10):
... linked_list.insert_nth(i, i)
>>> linked_list[0] = 666
>>> linked_list[0]
666
>>> linked_list[5] = -666
>>> linked_list[5]
-666
>>> linked_list[-10] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
>>> linked_list[len(linked_list)] = 666
Traceback (most recent call last):
...
ValueError: list index out of range.
"""
if not 0 <= index < len(self):
raise ValueError("list index out of range.")
current = self.head
for _ in range(index):
current = current.next_node
current.data = data
def insert_tail(self, data: Any) -> None:
"""
Insert data to the end of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("tail")
>>> linked_list
tail
>>> linked_list.insert_tail("tail_2")
>>> linked_list
tail -> tail_2
>>> linked_list.insert_tail("tail_3")
>>> linked_list
tail -> tail_2 -> tail_3
"""
self.insert_nth(len(self), data)
def insert_head(self, data: Any) -> None:
"""
Insert data to the beginning of linked list.
>>> linked_list = LinkedList()
>>> linked_list.insert_head("head")
>>> linked_list
head
>>> linked_list.insert_head("head_2")
>>> linked_list
head_2 -> head
>>> linked_list.insert_head("head_3")
>>> linked_list
head_3 -> head_2 -> head
"""
self.insert_nth(0, data)
def insert_nth(self, index: int, data: Any) -> None:
"""
Insert data at given index.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.insert_nth(1, "fourth")
>>> linked_list
first -> fourth -> second -> third
>>> linked_list.insert_nth(3, "fifth")
>>> linked_list
first -> fourth -> second -> fifth -> third
"""
if not 0 <= index <= len(self):
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = new_node
elif index == 0:
new_node.next_node = self.head # link new_node to head
self.head = new_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next_node
new_node.next_node = temp.next_node
temp.next_node = new_node
def print_list(self) -> None: # print every node data
"""
This method prints every node data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
"""
print(self)
def delete_head(self) -> Any:
"""
Delete the first node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.delete_head()
'first'
>>> linked_list
second -> third
>>> linked_list.delete_head()
'second'
>>> linked_list
third
>>> linked_list.delete_head()
'third'
>>> linked_list.delete_head()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(0)
def delete_tail(self) -> Any: # delete from tail
"""
Delete the tail end node and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.delete_tail()
'third'
>>> linked_list
first -> second
>>> linked_list.delete_tail()
'second'
>>> linked_list
first
>>> linked_list.delete_tail()
'first'
>>> linked_list.delete_tail()
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
return self.delete_nth(len(self) - 1)
def delete_nth(self, index: int = 0) -> Any:
"""
Delete node at given index and return the
node's data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.delete_nth(1) # delete middle
'second'
>>> linked_list
first -> third
>>> linked_list.delete_nth(5) # this raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
>>> linked_list.delete_nth(-1) # this also raises error
Traceback (most recent call last):
...
IndexError: List index out of range.
"""
if not 0 <= index <= len(self) - 1: # test if index is valid
raise IndexError("List index out of range.")
delete_node = self.head # default first node
if index == 0:
self.head = self.head.next_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next_node
delete_node = temp.next_node
temp.next_node = temp.next_node.next_node
return delete_node.data
def is_empty(self) -> bool:
"""
Check if linked list is empty.
>>> linked_list = LinkedList()
>>> linked_list.is_empty()
True
>>> linked_list.insert_head("first")
>>> linked_list.is_empty()
False
"""
return self.head is None
def reverse(self) -> None:
"""
This reverses the linked list order.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.reverse()
>>> linked_list
third -> second -> first
"""
prev = None
current = self.head
while current:
# Store the current node's next node.
next_node = current.next_node
# Make the current node's next_node point backwards
current.next_node = prev
# Make the previous node be the current node
prev = current
# Make the current node the next_node node (to progress iteration)
current = next_node
# Return prev in order to put the head at the end
self.head = prev
def test_singly_linked_list() -> None:
"""
>>> test_singly_linked_list()
"""
linked_list = LinkedList()
assert linked_list.is_empty() is True
assert str(linked_list) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10):
assert len(linked_list) == i
linked_list.insert_nth(i, i + 1)
assert str(linked_list) == " -> ".join(str(i) for i in range(1, 11))
linked_list.insert_head(0)
linked_list.insert_tail(11)
assert str(linked_list) == " -> ".join(str(i) for i in range(12))
assert linked_list.delete_head() == 0
assert linked_list.delete_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == " -> ".join(str(i) for i in range(1, 10))
assert all(linked_list[i] == i + 1 for i in range(9)) is True
for i in range(9):
linked_list[i] = -i
assert all(linked_list[i] == -i for i in range(9)) is True
linked_list.reverse()
assert str(linked_list) == " -> ".join(str(i) for i in range(-8, 1))
def test_singly_linked_list_2() -> None:
"""
This section of the test used varying data types for input.
>>> test_singly_linked_list_2()
"""
test_input = [
-9,
100,
Node(77345112),
"dlrow olleH",
7,
5555,
0,
-192.55555,
"Hello, world!",
77.9,
Node(10),
None,
None,
12.20,
]
linked_list = LinkedList()
for i in test_input:
linked_list.insert_tail(i)
# Check if it's empty or not
assert linked_list.is_empty() is False
assert (
str(linked_list)
== "-9 -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> "
"0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2"
)
# Delete the head
result = linked_list.delete_head()
assert result == -9
assert (
str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> "
"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None -> 12.2"
)
# Delete the tail
result = linked_list.delete_tail()
assert result == 12.2
assert (
str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> "
"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None"
)
# Delete a node in specific location in linked list
result = linked_list.delete_nth(10)
assert result is None
assert (
str(linked_list) == "100 -> Node(77345112) -> dlrow olleH -> 7 -> 5555 -> 0 -> "
"-192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None"
)
# Add a Node instance to its head
linked_list.insert_head(Node("Hello again, world!"))
assert (
str(linked_list)
== "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> "
"7 -> 5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None"
)
# Add None to its tail
linked_list.insert_tail(None)
assert (
str(linked_list)
== "Node(Hello again, world!) -> 100 -> Node(77345112) -> dlrow olleH -> 7 -> "
"5555 -> 0 -> -192.55555 -> Hello, world! -> 77.9 -> Node(10) -> None -> None"
)
# Reverse the linked list
linked_list.reverse()
assert (
str(linked_list)
== "None -> None -> Node(10) -> 77.9 -> Hello, world! -> -192.55555 -> 0 -> "
"5555 -> 7 -> dlrow olleH -> Node(77345112) -> 100 -> Node(Hello again, world!)"
)
def main():
from doctest import testmod
testmod()
linked_list = LinkedList()
linked_list.insert_head(input("Inserting 1st at head ").strip())
linked_list.insert_head(input("Inserting 2nd at head ").strip())
print("\nPrint list:")
linked_list.print_list()
linked_list.insert_tail(input("\nInserting 1st at tail ").strip())
linked_list.insert_tail(input("Inserting 2nd at tail ").strip())
print("\nPrint list:")
linked_list.print_list()
print("\nDelete head")
linked_list.delete_head()
print("Delete tail")
linked_list.delete_tail()
print("\nPrint list:")
linked_list.print_list()
print("\nReverse linked list")
linked_list.reverse()
print("\nPrint list:")
linked_list.print_list()
print("\nString representation of linked list:")
print(linked_list)
print("\nReading/changing Node data using indexing:")
print(f"Element at Position 1: {linked_list[1]}")
linked_list[1] = input("Enter New Value: ").strip()
print("New list:")
print(linked_list)
print(f"length of linked_list is : {len(linked_list)}")
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/floyds_cycle_detection.py | data_structures/linked_list/floyds_cycle_detection.py | """
Floyd's cycle detection algorithm is a popular algorithm used to detect cycles
in a linked list. It uses two pointers, a slow pointer and a fast pointer,
to traverse the linked list. The slow pointer moves one node at a time while the fast
pointer moves two nodes at a time. If there is a cycle in the linked list,
the fast pointer will eventually catch up to the slow pointer and they will
meet at the same node. If there is no cycle, the fast pointer will reach the end of
the linked list and the algorithm will terminate.
For more information: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare
"""
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any, Self
@dataclass
class Node:
"""
A class representing a node in a singly linked list.
"""
data: Any
next_node: Self | None = None
@dataclass
class LinkedList:
"""
A class representing a singly linked list.
"""
head: Node | None = None
def __iter__(self) -> Iterator:
"""
Iterates through the linked list.
Returns:
Iterator: An iterator over the linked list.
Examples:
>>> linked_list = LinkedList()
>>> list(linked_list)
[]
>>> linked_list.add_node(1)
>>> tuple(linked_list)
(1,)
"""
visited = []
node = self.head
while node:
# Avoid infinite loop in there's a cycle
if node in visited:
return
visited.append(node)
yield node.data
node = node.next_node
def add_node(self, data: Any) -> None:
"""
Adds a new node to the end of the linked list.
Args:
data (Any): The data to be stored in the new node.
Examples:
>>> linked_list = LinkedList()
>>> linked_list.add_node(1)
>>> linked_list.add_node(2)
>>> linked_list.add_node(3)
>>> linked_list.add_node(4)
>>> tuple(linked_list)
(1, 2, 3, 4)
"""
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next_node is not None:
current_node = current_node.next_node
current_node.next_node = new_node
def detect_cycle(self) -> bool:
"""
Detects if there is a cycle in the linked list using
Floyd's cycle detection algorithm.
Returns:
bool: True if there is a cycle, False otherwise.
Examples:
>>> linked_list = LinkedList()
>>> linked_list.add_node(1)
>>> linked_list.add_node(2)
>>> linked_list.add_node(3)
>>> linked_list.add_node(4)
>>> linked_list.detect_cycle()
False
# Create a cycle in the linked list
>>> linked_list.head.next_node.next_node.next_node = linked_list.head.next_node
>>> linked_list.detect_cycle()
True
"""
if self.head is None:
return False
slow_pointer: Node | None = self.head
fast_pointer: Node | None = self.head
while fast_pointer is not None and fast_pointer.next_node is not None:
slow_pointer = slow_pointer.next_node if slow_pointer else None
fast_pointer = fast_pointer.next_node.next_node
if slow_pointer == fast_pointer:
return True
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.add_node(4)
# Create a cycle in the linked list
# It first checks if the head, next_node, and next_node.next_node attributes of the
# linked list are not None to avoid any potential type errors.
if (
linked_list.head
and linked_list.head.next_node
and linked_list.head.next_node.next_node
):
linked_list.head.next_node.next_node.next_node = linked_list.head.next_node
has_cycle = linked_list.detect_cycle()
print(has_cycle) # Output: True
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/swap_nodes.py | data_structures/linked_list/swap_nodes.py | from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
@dataclass
class Node:
data: Any
next_node: Node | None = None
@dataclass
class LinkedList:
head: Node | None = None
def __iter__(self) -> Iterator:
"""
>>> linked_list = LinkedList()
>>> list(linked_list)
[]
>>> linked_list.push(0)
>>> tuple(linked_list)
(0,)
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.push(0)
>>> len(linked_list)
1
"""
return sum(1 for _ in self)
def push(self, new_data: Any) -> None:
"""
Add a new node with the given data to the beginning of the Linked List.
Args:
new_data (Any): The data to be added to the new node.
Returns:
None
Examples:
>>> linked_list = LinkedList()
>>> linked_list.push(5)
>>> linked_list.push(4)
>>> linked_list.push(3)
>>> linked_list.push(2)
>>> linked_list.push(1)
>>> list(linked_list)
[1, 2, 3, 4, 5]
"""
new_node = Node(new_data)
new_node.next_node = self.head
self.head = new_node
def swap_nodes(self, node_data_1: Any, node_data_2: Any) -> None:
"""
Swap the positions of two nodes in the Linked List based on their data values.
Args:
node_data_1: Data value of the first node to be swapped.
node_data_2: Data value of the second node to be swapped.
Note:
If either of the specified data values isn't found then, no swapping occurs.
Examples:
When both values are present in a linked list.
>>> linked_list = LinkedList()
>>> linked_list.push(5)
>>> linked_list.push(4)
>>> linked_list.push(3)
>>> linked_list.push(2)
>>> linked_list.push(1)
>>> list(linked_list)
[1, 2, 3, 4, 5]
>>> linked_list.swap_nodes(1, 5)
>>> tuple(linked_list)
(5, 2, 3, 4, 1)
When one value is present and the other isn't in the linked list.
>>> second_list = LinkedList()
>>> second_list.push(6)
>>> second_list.push(7)
>>> second_list.push(8)
>>> second_list.push(9)
>>> second_list.swap_nodes(1, 6) is None
True
When both values are absent in the linked list.
>>> second_list = LinkedList()
>>> second_list.push(10)
>>> second_list.push(9)
>>> second_list.push(8)
>>> second_list.push(7)
>>> second_list.swap_nodes(1, 3) is None
True
When linkedlist is empty.
>>> second_list = LinkedList()
>>> second_list.swap_nodes(1, 3) is None
True
Returns:
None
"""
if node_data_1 == node_data_2:
return
node_1 = self.head
while node_1 and node_1.data != node_data_1:
node_1 = node_1.next_node
node_2 = self.head
while node_2 and node_2.data != node_data_2:
node_2 = node_2.next_node
if node_1 is None or node_2 is None:
return
# Swap the data values of the two nodes
node_1.data, node_2.data = node_2.data, node_1.data
if __name__ == "__main__":
"""
Python script that outputs the swap of nodes in a linked list.
"""
from doctest import testmod
testmod()
linked_list = LinkedList()
for i in range(5, 0, -1):
linked_list.push(i)
print(f"Original Linked List: {list(linked_list)}")
linked_list.swap_nodes(1, 4)
print(f"Modified Linked List: {list(linked_list)}")
print("After swapping the nodes whose data is 1 and 4.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/from_sequence.py | data_structures/linked_list/from_sequence.py | """
Recursive Program to create a Linked List from a sequence and
print a string representation of it.
"""
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
def __repr__(self):
"""Returns a visual representation of the node and all its following nodes."""
string_rep = ""
temp = self
while temp:
string_rep += f"<{temp.data}> ---> "
temp = temp.next
string_rep += "<END>"
return string_rep
def make_linked_list(elements_list: list | tuple) -> Node:
"""
Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List.
>>> make_linked_list([])
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list(())
Traceback (most recent call last):
...
ValueError: The Elements List is empty
>>> make_linked_list([1])
<1> ---> <END>
>>> make_linked_list((1,))
<1> ---> <END>
>>> make_linked_list([1, 3, 5, 32, 44, 12, 43])
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
>>> make_linked_list((1, 3, 5, 32, 44, 12, 43))
<1> ---> <3> ---> <5> ---> <32> ---> <44> ---> <12> ---> <43> ---> <END>
"""
# if elements_list is empty
if not elements_list:
raise ValueError("The Elements List is empty")
# Set first element as Head
head = Node(elements_list[0])
current = head
# Loop through elements from position 1
for data in elements_list[1:]:
current.next = Node(data)
current = current.next
return head
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/circular_linked_list.py | data_structures/linked_list/circular_linked_list.py | from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
@dataclass
class Node:
data: Any
next_node: Node | None = None
@dataclass
class CircularLinkedList:
head: Node | None = None # Reference to the head (first node)
tail: Node | None = None # Reference to the tail (last node)
def __iter__(self) -> Iterator[Any]:
"""
Iterate through all nodes in the Circular Linked List yielding their data.
Yields:
The data of each node in the linked list.
"""
node = self.head
while node:
yield node.data
node = node.next_node
if node == self.head:
break
def __len__(self) -> int:
"""
Get the length (number of nodes) in the Circular Linked List.
"""
return sum(1 for _ in self)
def __repr__(self) -> str:
"""
Generate a string representation of the Circular Linked List.
Returns:
A string of the format "1->2->....->N".
"""
return "->".join(str(item) for item in iter(self))
def insert_tail(self, data: Any) -> None:
"""
Insert a node with the given data at the end of the Circular Linked List.
"""
self.insert_nth(len(self), data)
def insert_head(self, data: Any) -> None:
"""
Insert a node with the given data at the beginning of the Circular Linked List.
"""
self.insert_nth(0, data)
def insert_nth(self, index: int, data: Any) -> None:
"""
Insert the data of the node at the nth pos in the Circular Linked List.
Args:
index: The index at which the data should be inserted.
data: The data to be inserted.
Raises:
IndexError: If the index is out of range.
"""
if index < 0 or index > len(self):
raise IndexError("list index out of range.")
new_node: Node = Node(data)
if self.head is None:
new_node.next_node = new_node # First node points to itself
self.tail = self.head = new_node
elif index == 0: # Insert at the head
new_node.next_node = self.head
assert self.tail is not None # List is not empty, tail exists
self.head = self.tail.next_node = new_node
else:
temp: Node | None = self.head
for _ in range(index - 1):
assert temp is not None
temp = temp.next_node
assert temp is not None
new_node.next_node = temp.next_node
temp.next_node = new_node
if index == len(self) - 1: # Insert at the tail
self.tail = new_node
def delete_front(self) -> Any:
"""
Delete and return the data of the node at the front of the Circular Linked List.
Raises:
IndexError: If the list is empty.
"""
return self.delete_nth(0)
def delete_tail(self) -> Any:
"""
Delete and return the data of the node at the end of the Circular Linked List.
Returns:
Any: The data of the deleted node.
Raises:
IndexError: If the index is out of range.
"""
return self.delete_nth(len(self) - 1)
def delete_nth(self, index: int = 0) -> Any:
"""
Delete and return the data of the node at the nth pos in Circular Linked List.
Args:
index (int): The index of the node to be deleted. Defaults to 0.
Returns:
Any: The data of the deleted node.
Raises:
IndexError: If the index is out of range.
"""
if not 0 <= index < len(self):
raise IndexError("list index out of range.")
assert self.head is not None
assert self.tail is not None
delete_node: Node = self.head
if self.head == self.tail: # Just one node
self.head = self.tail = None
elif index == 0: # Delete head node
assert self.tail.next_node is not None
self.tail.next_node = self.tail.next_node.next_node
self.head = self.head.next_node
else:
temp: Node | None = self.head
for _ in range(index - 1):
assert temp is not None
temp = temp.next_node
assert temp is not None
assert temp.next_node is not None
delete_node = temp.next_node
temp.next_node = temp.next_node.next_node
if index == len(self) - 1: # Delete at tail
self.tail = temp
return delete_node.data
def is_empty(self) -> bool:
"""
Check if the Circular Linked List is empty.
Returns:
bool: True if the list is empty, False otherwise.
"""
return len(self) == 0
def test_circular_linked_list() -> None:
"""
Test cases for the CircularLinkedList class.
>>> test_circular_linked_list()
"""
circular_linked_list = CircularLinkedList()
assert len(circular_linked_list) == 0
assert circular_linked_list.is_empty() is True
assert str(circular_linked_list) == ""
try:
circular_linked_list.delete_front()
raise AssertionError # This should not happen
except IndexError:
assert True # This should happen
try:
circular_linked_list.delete_tail()
raise AssertionError # This should not happen
except IndexError:
assert True # This should happen
try:
circular_linked_list.delete_nth(-1)
raise AssertionError
except IndexError:
assert True
try:
circular_linked_list.delete_nth(0)
raise AssertionError
except IndexError:
assert True
assert circular_linked_list.is_empty() is True
for i in range(5):
assert len(circular_linked_list) == i
circular_linked_list.insert_nth(i, i + 1)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6))
circular_linked_list.insert_tail(6)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7))
circular_linked_list.insert_head(0)
assert str(circular_linked_list) == "->".join(str(i) for i in range(7))
assert circular_linked_list.delete_front() == 0
assert circular_linked_list.delete_tail() == 6
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6))
assert circular_linked_list.delete_nth(2) == 3
circular_linked_list.insert_nth(2, 3)
assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6))
assert circular_linked_list.is_empty() is False
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/doubly_linked_list_two.py | data_structures/linked_list/doubly_linked_list_two.py | """
- A linked list is similar to an array, it holds values. However, links in a linked
list do not have indexes.
- This is an example of a double ended, doubly linked list.
- Each link references the next link and the previous one.
- A Doubly Linked List (DLL) contains an extra pointer, typically called previous
pointer, together with next pointer and data which are there in singly linked list.
- Advantages over SLL - It can be traversed in both forward and backward direction.
Delete operation is more efficient
"""
from dataclasses import dataclass
from typing import Self, TypeVar
DataType = TypeVar("DataType")
@dataclass
class Node[DataType]:
data: DataType
previous: Self | None = None
next: Self | None = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedListIterator:
def __init__(self, head):
self.current = head
def __iter__(self):
return self
def __next__(self):
if not self.current:
raise StopIteration
else:
value = self.current.data
self.current = self.current.next
return value
@dataclass
class LinkedList:
head: Node | None = None # First node in list
tail: Node | None = None # Last node in list
def __str__(self):
current = self.head
nodes = []
while current is not None:
nodes.append(current.data)
current = current.next
return " ".join(str(node) for node in nodes)
def __contains__(self, value: DataType):
current = self.head
while current:
if current.data == value:
return True
current = current.next
return False
def __iter__(self):
return LinkedListIterator(self.head)
def get_head_data(self):
if self.head:
return self.head.data
return None
def get_tail_data(self):
if self.tail:
return self.tail.data
return None
def set_head(self, node: Node) -> None:
if self.head is None:
self.head = node
self.tail = node
else:
self.insert_before_node(self.head, node)
def set_tail(self, node: Node) -> None:
if self.tail is None:
self.head = node
self.tail = node
else:
self.insert_after_node(self.tail, node)
def insert(self, value: DataType) -> None:
node = Node(value)
if self.head is None:
self.set_head(node)
else:
self.set_tail(node)
def insert_before_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.next = node
node_to_insert.previous = node.previous
if node.previous is None:
self.head = node_to_insert
else:
node.previous.next = node_to_insert
node.previous = node_to_insert
def insert_after_node(self, node: Node, node_to_insert: Node) -> None:
node_to_insert.previous = node
node_to_insert.next = node.next
if node.next is None:
self.tail = node_to_insert
else:
node.next.previous = node_to_insert
node.next = node_to_insert
def insert_at_position(self, position: int, value: DataType) -> None:
current_position = 1
new_node = Node(value)
node = self.head
while node:
if current_position == position:
self.insert_before_node(node, new_node)
return
current_position += 1
node = node.next
self.set_tail(new_node)
def get_node(self, item: DataType) -> Node:
node = self.head
while node:
if node.data == item:
return node
node = node.next
raise Exception("Node not found")
def delete_value(self, value):
if (node := self.get_node(value)) is not None:
if node == self.head:
self.head = self.head.next
if node == self.tail:
self.tail = self.tail.previous
self.remove_node_pointers(node)
@staticmethod
def remove_node_pointers(node: Node) -> None:
if node.next:
node.next.previous = node.previous
if node.previous:
node.previous.next = node.next
node.next = None
node.previous = None
def is_empty(self):
return self.head is None
def create_linked_list() -> None:
"""
>>> new_linked_list = LinkedList()
>>> new_linked_list.get_head_data() is None
True
>>> new_linked_list.get_tail_data() is None
True
>>> new_linked_list.is_empty()
True
>>> new_linked_list.insert(10)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
10
>>> new_linked_list.insert_at_position(position=3, value=20)
>>> new_linked_list.get_head_data()
10
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_head(Node(1000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.set_tail(Node(2000))
>>> new_linked_list.get_head_data()
1000
>>> new_linked_list.get_tail_data()
2000
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> new_linked_list.is_empty()
False
>>> for value in new_linked_list:
... print(value)
1000
10
20
2000
>>> 10 in new_linked_list
True
>>> new_linked_list.delete_value(value=10)
>>> 10 in new_linked_list
False
>>> new_linked_list.delete_value(value=2000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.delete_value(value=1000)
>>> new_linked_list.get_tail_data()
20
>>> new_linked_list.get_head_data()
20
>>> for value in new_linked_list:
... print(value)
20
>>> new_linked_list.delete_value(value=20)
>>> for value in new_linked_list:
... print(value)
>>> for value in range(1,10):
... new_linked_list.insert(value=value)
>>> for value in new_linked_list:
... print(value)
1
2
3
4
5
6
7
8
9
>>> linked_list = LinkedList()
>>> linked_list.insert_at_position(position=1, value=10)
>>> str(linked_list)
'10'
>>> linked_list.insert_at_position(position=2, value=20)
>>> str(linked_list)
'10 20'
>>> linked_list.insert_at_position(position=1, value=30)
>>> str(linked_list)
'30 10 20'
>>> linked_list.insert_at_position(position=3, value=40)
>>> str(linked_list)
'30 10 40 20'
>>> linked_list.insert_at_position(position=5, value=50)
>>> str(linked_list)
'30 10 40 20 50'
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/is_palindrome.py | data_structures/linked_list/is_palindrome.py | from __future__ import annotations
from dataclasses import dataclass
@dataclass
class ListNode:
val: int = 0
next_node: ListNode | None = None
def is_palindrome(head: ListNode | None) -> bool:
"""
Check if a linked list is a palindrome.
Args:
head: The head of the linked list.
Returns:
bool: True if the linked list is a palindrome, False otherwise.
Examples:
>>> is_palindrome(None)
True
>>> is_palindrome(ListNode(1))
True
>>> is_palindrome(ListNode(1, ListNode(2)))
False
>>> is_palindrome(ListNode(1, ListNode(2, ListNode(1))))
True
>>> is_palindrome(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))
True
"""
if not head:
return True
# split the list to two parts
fast: ListNode | None = head.next_node
slow: ListNode | None = head
while fast and fast.next_node:
fast = fast.next_node.next_node
slow = slow.next_node if slow else None
if slow:
# slow will always be defined,
# adding this check to resolve mypy static check
second = slow.next_node
slow.next_node = None # Don't forget here! But forget still works!
# reverse the second part
node: ListNode | None = None
while second:
nxt = second.next_node
second.next_node = node
node = second
second = nxt
# compare two parts
# second part has the same or one less node
while node and head:
if node.val != head.val:
return False
node = node.next_node
head = head.next_node
return True
def is_palindrome_stack(head: ListNode | None) -> bool:
"""
Check if a linked list is a palindrome using a stack.
Args:
head (ListNode): The head of the linked list.
Returns:
bool: True if the linked list is a palindrome, False otherwise.
Examples:
>>> is_palindrome_stack(None)
True
>>> is_palindrome_stack(ListNode(1))
True
>>> is_palindrome_stack(ListNode(1, ListNode(2)))
False
>>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(1))))
True
>>> is_palindrome_stack(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))
True
"""
if not head or not head.next_node:
return True
# 1. Get the midpoint (slow)
slow: ListNode | None = head
fast: ListNode | None = head
while fast and fast.next_node:
fast = fast.next_node.next_node
slow = slow.next_node if slow else None
# slow will always be defined,
# adding this check to resolve mypy static check
if slow:
stack = [slow.val]
# 2. Push the second half into the stack
while slow.next_node:
slow = slow.next_node
stack.append(slow.val)
# 3. Comparison
cur: ListNode | None = head
while stack and cur:
if stack.pop() != cur.val:
return False
cur = cur.next_node
return True
def is_palindrome_dict(head: ListNode | None) -> bool:
"""
Check if a linked list is a palindrome using a dictionary.
Args:
head (ListNode): The head of the linked list.
Returns:
bool: True if the linked list is a palindrome, False otherwise.
Examples:
>>> is_palindrome_dict(None)
True
>>> is_palindrome_dict(ListNode(1))
True
>>> is_palindrome_dict(ListNode(1, ListNode(2)))
False
>>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(1))))
True
>>> is_palindrome_dict(ListNode(1, ListNode(2, ListNode(2, ListNode(1)))))
True
>>> is_palindrome_dict(
... ListNode(
... 1, ListNode(2, ListNode(1, ListNode(3, ListNode(2, ListNode(1)))))
... )
... )
False
"""
if not head or not head.next_node:
return True
d: dict[int, list[int]] = {}
pos = 0
while head:
if head.val in d:
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next_node
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
for step, i in enumerate(range(len(v))):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
if middle > 1:
return False
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/has_loop.py | data_structures/linked_list/has_loop.py | from __future__ import annotations
from typing import Any
class ContainsLoopError(Exception):
pass
class Node:
def __init__(self, data: Any) -> None:
self.data: Any = data
self.next_node: Node | None = None
def __iter__(self):
node = self
visited = set()
while node:
if node in visited:
raise ContainsLoopError
visited.add(node)
yield node.data
node = node.next_node
@property
def has_loop(self) -> bool:
"""
A loop is when the exact same Node appears more than once in a linked list.
>>> root_node = Node(1)
>>> root_node.next_node = Node(2)
>>> root_node.next_node.next_node = Node(3)
>>> root_node.next_node.next_node.next_node = Node(4)
>>> root_node.has_loop
False
>>> root_node.next_node.next_node.next_node = root_node.next_node
>>> root_node.has_loop
True
"""
try:
list(self)
return False
except ContainsLoopError:
return True
if __name__ == "__main__":
root_node = Node(1)
root_node.next_node = Node(2)
root_node.next_node.next_node = Node(3)
root_node.next_node.next_node.next_node = Node(4)
print(root_node.has_loop) # False
root_node.next_node.next_node.next_node = root_node.next_node
print(root_node.has_loop) # True
root_node = Node(5)
root_node.next_node = Node(6)
root_node.next_node.next_node = Node(5)
root_node.next_node.next_node.next_node = Node(6)
print(root_node.has_loop) # False
root_node = Node(1)
print(root_node.has_loop) # False
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/middle_element_of_linked_list.py | data_structures/linked_list/middle_element_of_linked_list.py | from __future__ import annotations
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data: int) -> int:
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
return self.head.data
def middle_element(self) -> int | None:
"""
>>> link = LinkedList()
>>> link.middle_element()
No element found.
>>> link.push(5)
5
>>> link.push(6)
6
>>> link.push(8)
8
>>> link.push(8)
8
>>> link.push(10)
10
>>> link.push(12)
12
>>> link.push(17)
17
>>> link.push(7)
7
>>> link.push(3)
3
>>> link.push(20)
20
>>> link.push(-20)
-20
>>> link.middle_element()
12
>>>
"""
slow_pointer = self.head
fast_pointer = self.head
if self.head:
while fast_pointer and fast_pointer.next:
fast_pointer = fast_pointer.next.next
slow_pointer = slow_pointer.next
return slow_pointer.data
else:
print("No element found.")
return None
if __name__ == "__main__":
link = LinkedList()
for _ in range(int(input().strip())):
data = int(input().strip())
link.push(data)
print(link.middle_element())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/rotate_to_the_right.py | data_structures/linked_list/rotate_to_the_right.py | from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
data: int
next_node: Node | None = None
def print_linked_list(head: Node | None) -> None:
"""
Print the entire linked list iteratively.
This function prints the elements of a linked list separated by '->'.
Parameters:
head (Node | None): The head of the linked list to be printed,
or None if the linked list is empty.
>>> head = insert_node(None, 0)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 1)
>>> print_linked_list(head)
0->2->1
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> print_linked_list(head)
0->2->1->4->5
"""
if head is None:
return
while head.next_node is not None:
print(head.data, end="->")
head = head.next_node
print(head.data)
def insert_node(head: Node | None, data: int) -> Node:
"""
Insert a new node at the end of a linked list and return the new head.
Parameters:
head (Node | None): The head of the linked list.
data (int): The data to be inserted into the new node.
Returns:
Node: The new head of the linked list.
>>> head = insert_node(None, 10)
>>> head = insert_node(head, 9)
>>> head = insert_node(head, 8)
>>> print_linked_list(head)
10->9->8
"""
new_node = Node(data)
# If the linked list is empty, the new_node becomes the head
if head is None:
return new_node
temp_node = head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = new_node
return head
def rotate_to_the_right(head: Node, places: int) -> Node:
"""
Rotate a linked list to the right by places times.
Parameters:
head: The head of the linked list.
places: The number of places to rotate.
Returns:
Node: The head of the rotated linked list.
>>> rotate_to_the_right(None, places=1)
Traceback (most recent call last):
...
ValueError: The linked list is empty.
>>> head = insert_node(None, 1)
>>> rotate_to_the_right(head, places=1) == head
True
>>> head = insert_node(None, 1)
>>> head = insert_node(head, 2)
>>> head = insert_node(head, 3)
>>> head = insert_node(head, 4)
>>> head = insert_node(head, 5)
>>> new_head = rotate_to_the_right(head, places=2)
>>> print_linked_list(new_head)
4->5->1->2->3
"""
# Check if the list is empty or has only one element
if not head:
raise ValueError("The linked list is empty.")
if head.next_node is None:
return head
# Calculate the length of the linked list
length = 1
temp_node = head
while temp_node.next_node is not None:
length += 1
temp_node = temp_node.next_node
# Adjust the value of places to avoid places longer than the list.
places %= length
if places == 0:
return head # As no rotation is needed.
# Find the new head position after rotation.
new_head_index = length - places
# Traverse to the new head position
temp_node = head
for _ in range(new_head_index - 1):
assert temp_node.next_node
temp_node = temp_node.next_node
# Update pointers to perform rotation
assert temp_node.next_node
new_head = temp_node.next_node
temp_node.next_node = None
temp_node = new_head
while temp_node.next_node:
temp_node = temp_node.next_node
temp_node.next_node = head
assert new_head
return new_head
if __name__ == "__main__":
import doctest
doctest.testmod()
head = insert_node(None, 5)
head = insert_node(head, 1)
head = insert_node(head, 2)
head = insert_node(head, 4)
head = insert_node(head, 3)
print("Original list: ", end="")
print_linked_list(head)
places = 3
new_head = rotate_to_the_right(head, places)
print(f"After {places} iterations: ", end="")
print_linked_list(new_head)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/deque_doubly.py | data_structures/linked_list/deque_doubly.py | """
Implementing Deque using DoublyLinkedList ...
Operations:
1. insertion in the front -> O(1)
2. insertion in the end -> O(1)
3. remove from the front -> O(1)
4. remove from the end -> O(1)
"""
class _DoublyLinkedBase:
"""A Private class (to be inherited)"""
class _Node:
__slots__ = "_data", "_next", "_prev"
def __init__(self, link_p, element, link_n):
self._prev = link_p
self._data = element
self._next = link_n
def has_next_and_prev(self):
return (
f" Prev -> {self._prev is not None}, Next -> {self._next is not None}"
)
def __init__(self):
self._header = self._Node(None, None, None)
self._trailer = self._Node(None, None, None)
self._header._next = self._trailer
self._trailer._prev = self._header
self._size = 0
def __len__(self):
return self._size
def is_empty(self):
return self.__len__() == 0
def _insert(self, predecessor, e, successor):
# Create new_node by setting it's prev.link -> header
# setting it's next.link -> trailer
new_node = self._Node(predecessor, e, successor)
predecessor._next = new_node
successor._prev = new_node
self._size += 1
return self
def _delete(self, node):
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self._size -= 1
temp = node._data
node._prev = node._next = node._data = None
del node
return temp
class LinkedDeque(_DoublyLinkedBase):
def first(self):
"""return first element
>>> d = LinkedDeque()
>>> d.add_first('A').first()
'A'
>>> d.add_first('B').first()
'B'
"""
if self.is_empty():
raise Exception("List is empty")
return self._header._next._data
def last(self):
"""return last element
>>> d = LinkedDeque()
>>> d.add_last('A').last()
'A'
>>> d.add_last('B').last()
'B'
"""
if self.is_empty():
raise Exception("List is empty")
return self._trailer._prev._data
# DEque Insert Operations (At the front, At the end)
def add_first(self, element):
"""insertion in the front
>>> LinkedDeque().add_first('AV').first()
'AV'
"""
return self._insert(self._header, element, self._header._next)
def add_last(self, element):
"""insertion in the end
>>> LinkedDeque().add_last('B').last()
'B'
"""
return self._insert(self._trailer._prev, element, self._trailer)
# DEqueu Remove Operations (At the front, At the end)
def remove_first(self):
"""removal from the front
>>> d = LinkedDeque()
>>> d.is_empty()
True
>>> d.remove_first()
Traceback (most recent call last):
...
IndexError: remove_first from empty list
>>> d.add_first('A') # doctest: +ELLIPSIS
<data_structures.linked_list.deque_doubly.LinkedDeque object at ...
>>> d.remove_first()
'A'
>>> d.is_empty()
True
"""
if self.is_empty():
raise IndexError("remove_first from empty list")
return self._delete(self._header._next)
def remove_last(self):
"""removal in the end
>>> d = LinkedDeque()
>>> d.is_empty()
True
>>> d.remove_last()
Traceback (most recent call last):
...
IndexError: remove_first from empty list
>>> d.add_first('A') # doctest: +ELLIPSIS
<data_structures.linked_list.deque_doubly.LinkedDeque object at ...
>>> d.remove_last()
'A'
>>> d.is_empty()
True
"""
if self.is_empty():
raise IndexError("remove_first from empty list")
return self._delete(self._trailer._prev)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/__init__.py | data_structures/linked_list/__init__.py | """
Linked Lists consists of Nodes.
Nodes contain data and also may link to other nodes:
- Head Node: First node, the address of the
head node gives us access of the complete list
- Last node: points to null
"""
from __future__ import annotations
from typing import Any
class Node:
def __init__(self, item: Any, next: Any) -> None: # noqa: A002
self.item = item
self.next = next
class LinkedList:
def __init__(self) -> None:
self.head: Node | None = None
self.size = 0
def add(self, item: Any, position: int = 0) -> None:
"""
Add an item to the LinkedList at the specified position.
Default position is 0 (the head).
Args:
item (Any): The item to add to the LinkedList.
position (int, optional): The position at which to add the item.
Defaults to 0.
Raises:
ValueError: If the position is negative or out of bounds.
>>> linked_list = LinkedList()
>>> linked_list.add(1)
>>> linked_list.add(2)
>>> linked_list.add(3)
>>> linked_list.add(4, 2)
>>> print(linked_list)
3 --> 2 --> 4 --> 1
# Test adding to a negative position
>>> linked_list.add(5, -3)
Traceback (most recent call last):
...
ValueError: Position must be non-negative
# Test adding to an out-of-bounds position
>>> linked_list.add(5,7)
Traceback (most recent call last):
...
ValueError: Out of bounds
>>> linked_list.add(5, 4)
>>> print(linked_list)
3 --> 2 --> 4 --> 1 --> 5
"""
if position < 0:
raise ValueError("Position must be non-negative")
if position == 0 or self.head is None:
new_node = Node(item, self.head)
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
current = current.next
if current is None:
raise ValueError("Out of bounds")
new_node = Node(item, current.next)
current.next = new_node
self.size += 1
def remove(self) -> Any:
# Switched 'self.is_empty()' to 'self.head is None'
# because mypy was considering the possibility that 'self.head'
# can be None in below else part and giving error
if self.head is None:
return None
else:
item = self.head.item
self.head = self.head.next
self.size -= 1
return item
def is_empty(self) -> bool:
return self.head is None
def __str__(self) -> str:
"""
>>> linked_list = LinkedList()
>>> linked_list.add(23)
>>> linked_list.add(14)
>>> linked_list.add(9)
>>> print(linked_list)
9 --> 14 --> 23
"""
if self.is_empty():
return ""
else:
iterate = self.head
item_str = ""
item_list: list[str] = []
while iterate:
item_list.append(str(iterate.item))
iterate = iterate.next
item_str = " --> ".join(item_list)
return item_str
def __len__(self) -> int:
"""
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.add("a")
>>> len(linked_list)
1
>>> linked_list.add("b")
>>> len(linked_list)
2
>>> _ = linked_list.remove()
>>> len(linked_list)
1
>>> _ = linked_list.remove()
>>> len(linked_list)
0
"""
return self.size
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/reverse_k_group.py | data_structures/linked_list/reverse_k_group.py | from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
@dataclass
class Node:
data: int
next_node: Node | None = None
class LinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in ints:
self.append(i)
def __iter__(self) -> Iterator[int]:
"""
>>> ints = []
>>> list(LinkedList(ints)) == ints
True
>>> ints = tuple(range(5))
>>> tuple(LinkedList(ints)) == ints
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(LinkedList(range(i))) == i
True
True
True
>>> len(LinkedList("abcdefgh"))
8
"""
return sum(1 for _ in self)
def __str__(self) -> str:
"""
>>> str(LinkedList([]))
''
>>> str(LinkedList(range(5)))
'0 -> 1 -> 2 -> 3 -> 4'
"""
return " -> ".join([str(node) for node in self])
def append(self, data: int) -> None:
"""
>>> ll = LinkedList([1, 2])
>>> tuple(ll)
(1, 2)
>>> ll.append(3)
>>> tuple(ll)
(1, 2, 3)
>>> ll.append(4)
>>> tuple(ll)
(1, 2, 3, 4)
>>> len(ll)
4
"""
if not self.head:
self.head = Node(data)
return
node = self.head
while node.next_node:
node = node.next_node
node.next_node = Node(data)
def reverse_k_nodes(self, group_size: int) -> None:
"""
reverse nodes within groups of size k
>>> ll = LinkedList([1, 2, 3, 4, 5])
>>> ll.reverse_k_nodes(2)
>>> tuple(ll)
(2, 1, 4, 3, 5)
>>> str(ll)
'2 -> 1 -> 4 -> 3 -> 5'
"""
if self.head is None or self.head.next_node is None:
return
length = len(self)
dummy_head = Node(0)
dummy_head.next_node = self.head
previous_node = dummy_head
while length >= group_size:
current_node = previous_node.next_node
assert current_node
next_node = current_node.next_node
for _ in range(1, group_size):
assert next_node, current_node
current_node.next_node = next_node.next_node
assert previous_node
next_node.next_node = previous_node.next_node
previous_node.next_node = next_node
next_node = current_node.next_node
previous_node = current_node
length -= group_size
self.head = dummy_head.next_node
if __name__ == "__main__":
import doctest
doctest.testmod()
ll = LinkedList([1, 2, 3, 4, 5])
print(f"Original Linked List: {ll}")
k = 2
ll.reverse_k_nodes(k)
print(f"After reversing groups of size {k}: {ll}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/skip_list.py | data_structures/linked_list/skip_list.py | """
Based on "Skip Lists: A Probabilistic Alternative to Balanced Trees" by William Pugh
https://epaperpress.com/sortsearch/download/skiplist.pdf
"""
from __future__ import annotations
from itertools import pairwise
from random import random
from typing import TypeVar
KT = TypeVar("KT")
VT = TypeVar("VT")
class Node[KT, VT]:
def __init__(self, key: KT | str = "root", value: VT | None = None):
self.key = key
self.value = value
self.forward: list[Node[KT, VT]] = []
def __repr__(self) -> str:
"""
:return: Visual representation of Node
>>> node = Node("Key", 2)
>>> repr(node)
'Node(Key: 2)'
"""
return f"Node({self.key}: {self.value})"
@property
def level(self) -> int:
"""
:return: Number of forward references
>>> node = Node("Key", 2)
>>> node.level
0
>>> node.forward.append(Node("Key2", 4))
>>> node.level
1
>>> node.forward.append(Node("Key3", 6))
>>> node.level
2
"""
return len(self.forward)
class SkipList[KT, VT]:
def __init__(self, p: float = 0.5, max_level: int = 16):
self.head: Node[KT, VT] = Node[KT, VT]()
self.level = 0
self.p = p
self.max_level = max_level
def __str__(self) -> str:
"""
:return: Visual representation of SkipList
>>> skip_list = SkipList()
>>> print(skip_list)
SkipList(level=0)
>>> skip_list.insert("Key1", "Value")
>>> print(skip_list) # doctest: +ELLIPSIS
SkipList(level=...
[root]--...
[Key1]--Key1...
None *...
>>> skip_list.insert("Key2", "OtherValue")
>>> print(skip_list) # doctest: +ELLIPSIS
SkipList(level=...
[root]--...
[Key1]--Key1...
[Key2]--Key2...
None *...
"""
items = list(self)
if len(items) == 0:
return f"SkipList(level={self.level})"
label_size = max((len(str(item)) for item in items), default=4)
label_size = max(label_size, 4) + 4
node = self.head
lines = []
forwards = node.forward.copy()
lines.append(f"[{node.key}]".ljust(label_size, "-") + "* " * len(forwards))
lines.append(" " * label_size + "| " * len(forwards))
while len(node.forward) != 0:
node = node.forward[0]
lines.append(
f"[{node.key}]".ljust(label_size, "-")
+ " ".join(str(n.key) if n.key == node.key else "|" for n in forwards)
)
lines.append(" " * label_size + "| " * len(forwards))
forwards[: node.level] = node.forward
lines.append("None".ljust(label_size) + "* " * len(forwards))
return f"SkipList(level={self.level})\n" + "\n".join(lines)
def __iter__(self):
node = self.head
while len(node.forward) != 0:
yield node.forward[0].key
node = node.forward[0]
def random_level(self) -> int:
"""
:return: Random level from [1, self.max_level] interval.
Higher values are less likely.
"""
level = 1
while random() < self.p and level < self.max_level:
level += 1
return level
def _locate_node(self, key) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]:
"""
:param key: Searched key,
:return: Tuple with searched node (or None if given key is not present)
and list of nodes that refer (if key is present) of should refer to
given node.
"""
# Nodes with refer or should refer to output node
update_vector = []
node = self.head
for i in reversed(range(self.level)):
# i < node.level - When node level is lesser than `i` decrement `i`.
# node.forward[i].key < key - Jumping to node with key value higher
# or equal to searched key would result
# in skipping searched key.
while i < node.level and node.forward[i].key < key:
node = node.forward[i]
# Each leftmost node (relative to searched node) will potentially have to
# be updated.
update_vector.append(node)
update_vector.reverse() # Note that we were inserting values in reverse order.
# len(node.forward) != 0 - If current node doesn't contain any further
# references then searched key is not present.
# node.forward[0].key == key - Next node key should be equal to search key
# if key is present.
if len(node.forward) != 0 and node.forward[0].key == key:
return node.forward[0], update_vector
else:
return None, update_vector
def delete(self, key: KT):
"""
:param key: Key to remove from list.
>>> skip_list = SkipList()
>>> skip_list.insert(2, "Two")
>>> skip_list.insert(1, "One")
>>> skip_list.insert(3, "Three")
>>> list(skip_list)
[1, 2, 3]
>>> skip_list.delete(2)
>>> list(skip_list)
[1, 3]
"""
node, update_vector = self._locate_node(key)
if node is not None:
for i, update_node in enumerate(update_vector):
# Remove or replace all references to removed node.
if update_node.level > i and update_node.forward[i].key == key:
if node.level > i:
update_node.forward[i] = node.forward[i]
else:
update_node.forward = update_node.forward[:i]
def insert(self, key: KT, value: VT):
"""
:param key: Key to insert.
:param value: Value associated with given key.
>>> skip_list = SkipList()
>>> skip_list.insert(2, "Two")
>>> skip_list.find(2)
'Two'
>>> list(skip_list)
[2]
"""
node, update_vector = self._locate_node(key)
if node is not None:
node.value = value
else:
level = self.random_level()
if level > self.level:
# After level increase we have to add additional nodes to head.
for _ in range(self.level - 1, level):
update_vector.append(self.head)
self.level = level
new_node = Node(key, value)
for i, update_node in enumerate(update_vector[:level]):
# Change references to pass through new node.
if update_node.level > i:
new_node.forward.append(update_node.forward[i])
if update_node.level < i + 1:
update_node.forward.append(new_node)
else:
update_node.forward[i] = new_node
def find(self, key: VT) -> VT | None:
"""
:param key: Search key.
:return: Value associated with given key or None if given key is not present.
>>> skip_list = SkipList()
>>> skip_list.find(2)
>>> skip_list.insert(2, "Two")
>>> skip_list.find(2)
'Two'
>>> skip_list.insert(2, "Three")
>>> skip_list.find(2)
'Three'
"""
node, _ = self._locate_node(key)
if node is not None:
return node.value
return None
def test_insert():
skip_list = SkipList()
skip_list.insert("Key1", 3)
skip_list.insert("Key2", 12)
skip_list.insert("Key3", 41)
skip_list.insert("Key4", -19)
node = skip_list.head
all_values = {}
while node.level != 0:
node = node.forward[0]
all_values[node.key] = node.value
assert len(all_values) == 4
assert all_values["Key1"] == 3
assert all_values["Key2"] == 12
assert all_values["Key3"] == 41
assert all_values["Key4"] == -19
def test_insert_overrides_existing_value():
skip_list = SkipList()
skip_list.insert("Key1", 10)
skip_list.insert("Key1", 12)
skip_list.insert("Key5", 7)
skip_list.insert("Key7", 10)
skip_list.insert("Key10", 5)
skip_list.insert("Key7", 7)
skip_list.insert("Key5", 5)
skip_list.insert("Key10", 10)
node = skip_list.head
all_values = {}
while node.level != 0:
node = node.forward[0]
all_values[node.key] = node.value
if len(all_values) != 4:
print()
assert len(all_values) == 4
assert all_values["Key1"] == 12
assert all_values["Key7"] == 7
assert all_values["Key5"] == 5
assert all_values["Key10"] == 10
def test_searching_empty_list_returns_none():
skip_list = SkipList()
assert skip_list.find("Some key") is None
def test_search():
skip_list = SkipList()
skip_list.insert("Key2", 20)
assert skip_list.find("Key2") == 20
skip_list.insert("Some Key", 10)
skip_list.insert("Key2", 8)
skip_list.insert("V", 13)
assert skip_list.find("Y") is None
assert skip_list.find("Key2") == 8
assert skip_list.find("Some Key") == 10
assert skip_list.find("V") == 13
def test_deleting_item_from_empty_list_do_nothing():
skip_list = SkipList()
skip_list.delete("Some key")
assert len(skip_list.head.forward) == 0
def test_deleted_items_are_not_founded_by_find_method():
skip_list = SkipList()
skip_list.insert("Key1", 12)
skip_list.insert("V", 13)
skip_list.insert("X", 14)
skip_list.insert("Key2", 15)
skip_list.delete("V")
skip_list.delete("Key2")
assert skip_list.find("V") is None
assert skip_list.find("Key2") is None
def test_delete_removes_only_given_key():
skip_list = SkipList()
skip_list.insert("Key1", 12)
skip_list.insert("V", 13)
skip_list.insert("X", 14)
skip_list.insert("Key2", 15)
skip_list.delete("V")
assert skip_list.find("V") is None
assert skip_list.find("X") == 14
assert skip_list.find("Key1") == 12
assert skip_list.find("Key2") == 15
skip_list.delete("X")
assert skip_list.find("V") is None
assert skip_list.find("X") is None
assert skip_list.find("Key1") == 12
assert skip_list.find("Key2") == 15
skip_list.delete("Key1")
assert skip_list.find("V") is None
assert skip_list.find("X") is None
assert skip_list.find("Key1") is None
assert skip_list.find("Key2") == 15
skip_list.delete("Key2")
assert skip_list.find("V") is None
assert skip_list.find("X") is None
assert skip_list.find("Key1") is None
assert skip_list.find("Key2") is None
def test_delete_doesnt_leave_dead_nodes():
skip_list = SkipList()
skip_list.insert("Key1", 12)
skip_list.insert("V", 13)
skip_list.insert("X", 142)
skip_list.insert("Key2", 15)
skip_list.delete("X")
def traverse_keys(node):
yield node.key
for forward_node in node.forward:
yield from traverse_keys(forward_node)
assert len(set(traverse_keys(skip_list.head))) == 4
def test_iter_always_yields_sorted_values():
def is_sorted(lst):
return all(next_item >= item for item, next_item in pairwise(lst))
skip_list = SkipList()
for i in range(10):
skip_list.insert(i, i)
assert is_sorted(list(skip_list))
skip_list.delete(5)
skip_list.delete(8)
skip_list.delete(2)
assert is_sorted(list(skip_list))
skip_list.insert(-12, -12)
skip_list.insert(77, 77)
assert is_sorted(list(skip_list))
def pytests():
for _ in range(100):
# Repeat test 100 times due to the probabilistic nature of skip list
# random values == random bugs
test_insert()
test_insert_overrides_existing_value()
test_searching_empty_list_returns_none()
test_search()
test_deleting_item_from_empty_list_do_nothing()
test_deleted_items_are_not_founded_by_find_method()
test_delete_removes_only_given_key()
test_delete_doesnt_leave_dead_nodes()
test_iter_always_yields_sorted_values()
def main():
"""
>>> pytests()
"""
skip_list = SkipList()
skip_list.insert(2, "2")
skip_list.insert(4, "4")
skip_list.insert(6, "4")
skip_list.insert(4, "5")
skip_list.insert(8, "4")
skip_list.insert(9, "4")
skip_list.delete(4)
print(skip_list)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/merge_two_lists.py | data_structures/linked_list/merge_two_lists.py | """
Algorithm that merges two sorted linked lists into one sorted linked list.
"""
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1)
test_data_even = (4, 6, 2, 0, 8, 10, 3, -2)
@dataclass
class Node:
data: int
next_node: Node | None
class SortedLinkedList:
def __init__(self, ints: Iterable[int]) -> None:
self.head: Node | None = None
for i in sorted(ints, reverse=True):
self.head = Node(i, self.head)
def __iter__(self) -> Iterator[int]:
"""
>>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd))
True
>>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even))
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __len__(self) -> int:
"""
>>> for i in range(3):
... len(SortedLinkedList(range(i))) == i
True
True
True
>>> len(SortedLinkedList(test_data_odd))
8
"""
return sum(1 for _ in self)
def __str__(self) -> str:
"""
>>> str(SortedLinkedList([]))
''
>>> str(SortedLinkedList(test_data_odd))
'-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9'
>>> str(SortedLinkedList(test_data_even))
'-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10'
"""
return " -> ".join([str(node) for node in self])
def merge_lists(
sll_one: SortedLinkedList, sll_two: SortedLinkedList
) -> SortedLinkedList:
"""
>>> SSL = SortedLinkedList
>>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even))
>>> len(merged)
16
>>> str(merged)
'-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10'
>>> list(merged) == list(sorted(test_data_odd + test_data_even))
True
"""
return SortedLinkedList(list(sll_one) + list(sll_two))
if __name__ == "__main__":
import doctest
doctest.testmod()
SSL = SortedLinkedList
print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/doubly_linked_list.py | data_structures/linked_list/doubly_linked_list.py | """
https://en.wikipedia.org/wiki/Doubly_linked_list
"""
class Node:
def __init__(self, data):
self.data = data
self.previous = None
self.next = None
def __str__(self):
return f"{self.data}"
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.insert_at_head('b')
>>> linked_list.insert_at_head('a')
>>> linked_list.insert_at_tail('c')
>>> tuple(linked_list)
('a', 'b', 'c')
"""
node = self.head
while node:
yield node.data
node = node.next
def __str__(self):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.insert_at_tail('a')
>>> linked_list.insert_at_tail('b')
>>> linked_list.insert_at_tail('c')
>>> str(linked_list)
'a->b->c'
"""
return "->".join([str(item) for item in self])
def __len__(self):
"""
>>> linked_list = DoublyLinkedList()
>>> for i in range(0, 5):
... linked_list.insert_at_nth(i, i + 1)
>>> len(linked_list) == 5
True
"""
return sum(1 for _ in self)
def insert_at_head(self, data):
self.insert_at_nth(0, data)
def insert_at_tail(self, data):
self.insert_at_nth(len(self), data)
def insert_at_nth(self, index: int, data):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.insert_at_nth(-1, 666)
Traceback (most recent call last):
....
IndexError: list index out of range
>>> linked_list.insert_at_nth(1, 666)
Traceback (most recent call last):
....
IndexError: list index out of range
>>> linked_list.insert_at_nth(0, 2)
>>> linked_list.insert_at_nth(0, 1)
>>> linked_list.insert_at_nth(2, 4)
>>> linked_list.insert_at_nth(2, 3)
>>> str(linked_list)
'1->2->3->4'
>>> linked_list.insert_at_nth(5, 5)
Traceback (most recent call last):
....
IndexError: list index out of range
"""
length = len(self)
if not 0 <= index <= length:
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = self.tail = new_node
elif index == 0:
self.head.previous = new_node
new_node.next = self.head
self.head = new_node
elif index == length:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
else:
temp = self.head
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
new_node.next = temp
temp.previous = new_node
def delete_head(self):
return self.delete_at_nth(0)
def delete_tail(self):
return self.delete_at_nth(len(self) - 1)
def delete_at_nth(self, index: int):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.delete_at_nth(0)
Traceback (most recent call last):
....
IndexError: list index out of range
>>> for i in range(0, 5):
... linked_list.insert_at_nth(i, i + 1)
>>> linked_list.delete_at_nth(0) == 1
True
>>> linked_list.delete_at_nth(3) == 5
True
>>> linked_list.delete_at_nth(1) == 3
True
>>> str(linked_list)
'2->4'
>>> linked_list.delete_at_nth(2)
Traceback (most recent call last):
....
IndexError: list index out of range
"""
length = len(self)
if not 0 <= index <= length - 1:
raise IndexError("list index out of range")
delete_node = self.head # default first node
if length == 1:
self.head = self.tail = None
elif index == 0:
self.head = self.head.next
self.head.previous = None
elif index == length - 1:
delete_node = self.tail
self.tail = self.tail.previous
self.tail.next = None
else:
temp = self.head
for _ in range(index):
temp = temp.next
delete_node = temp
temp.next.previous = temp.previous
temp.previous.next = temp.next
return delete_node.data
def delete(self, data) -> str:
current = self.head
while current.data != data: # Find the position to delete
if current.next:
current = current.next
else: # We have reached the end an no value matches
raise ValueError("No data matching given value")
if current == self.head:
self.delete_head()
elif current == self.tail:
self.delete_tail()
else: # Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next # 1 --> 3
current.next.previous = current.previous # 1 <--> 3
return data
def is_empty(self):
"""
>>> linked_list = DoublyLinkedList()
>>> linked_list.is_empty()
True
>>> linked_list.insert_at_tail(1)
>>> linked_list.is_empty()
False
"""
return len(self) == 0
def test_doubly_linked_list() -> None:
"""
>>> test_doubly_linked_list()
"""
linked_list = DoublyLinkedList()
assert linked_list.is_empty() is True
assert str(linked_list) == ""
try:
linked_list.delete_head()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
try:
linked_list.delete_tail()
raise AssertionError # This should not happen.
except IndexError:
assert True # This should happen.
for i in range(10):
assert len(linked_list) == i
linked_list.insert_at_nth(i, i + 1)
assert str(linked_list) == "->".join(str(i) for i in range(1, 11))
linked_list.insert_at_head(0)
linked_list.insert_at_tail(11)
assert str(linked_list) == "->".join(str(i) for i in range(12))
assert linked_list.delete_head() == 0
assert linked_list.delete_at_nth(9) == 10
assert linked_list.delete_tail() == 11
assert len(linked_list) == 9
assert str(linked_list) == "->".join(str(i) for i in range(1, 10))
if __name__ == "__main__":
from doctest import testmod
testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/data_structures/linked_list/print_reverse.py | data_structures/linked_list/print_reverse.py | from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
@dataclass
class Node:
data: int
next_node: Node | None = None
class LinkedList:
"""A class to represent a Linked List.
Use a tail pointer to speed up the append() operation.
"""
def __init__(self) -> None:
"""Initialize a LinkedList with the head node set to None.
>>> linked_list = LinkedList()
>>> (linked_list.head, linked_list.tail)
(None, None)
"""
self.head: Node | None = None
self.tail: Node | None = None # Speeds up the append() operation
def __iter__(self) -> Iterator[int]:
"""Iterate the LinkedList yielding each Node's data.
>>> linked_list = LinkedList()
>>> items = (1, 2, 3, 4, 5)
>>> linked_list.extend(items)
>>> tuple(linked_list) == items
True
"""
node = self.head
while node:
yield node.data
node = node.next_node
def __repr__(self) -> str:
"""Returns a string representation of the LinkedList.
>>> linked_list = LinkedList()
>>> str(linked_list)
''
>>> linked_list.append(1)
>>> str(linked_list)
'1'
>>> linked_list.extend([2, 3, 4, 5])
>>> str(linked_list)
'1 -> 2 -> 3 -> 4 -> 5'
"""
return " -> ".join([str(data) for data in self])
def append(self, data: int) -> None:
"""Appends a new node with the given data to the end of the LinkedList.
>>> linked_list = LinkedList()
>>> str(linked_list)
''
>>> linked_list.append(1)
>>> str(linked_list)
'1'
>>> linked_list.append(2)
>>> str(linked_list)
'1 -> 2'
"""
if self.tail:
self.tail.next_node = self.tail = Node(data)
else:
self.head = self.tail = Node(data)
def extend(self, items: Iterable[int]) -> None:
"""Appends each item to the end of the LinkedList.
>>> linked_list = LinkedList()
>>> linked_list.extend([])
>>> str(linked_list)
''
>>> linked_list.extend([1, 2])
>>> str(linked_list)
'1 -> 2'
>>> linked_list.extend([3,4])
>>> str(linked_list)
'1 -> 2 -> 3 -> 4'
"""
for item in items:
self.append(item)
def make_linked_list(elements_list: Iterable[int]) -> LinkedList:
"""Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List.
>>> make_linked_list([])
Traceback (most recent call last):
...
Exception: The Elements List is empty
>>> make_linked_list([7])
7
>>> make_linked_list(['abc'])
abc
>>> make_linked_list([7, 25])
7 -> 25
"""
if not elements_list:
raise Exception("The Elements List is empty")
linked_list = LinkedList()
linked_list.extend(elements_list)
return linked_list
def in_reverse(linked_list: LinkedList) -> str:
"""Prints the elements of the given Linked List in reverse order
>>> in_reverse(LinkedList())
''
>>> in_reverse(make_linked_list([69, 88, 73]))
'73 <- 88 <- 69'
"""
return " <- ".join(str(line) for line in reversed(tuple(linked_list)))
if __name__ == "__main__":
from doctest import testmod
testmod()
linked_list = make_linked_list((14, 52, 14, 12, 43))
print(f"Linked List: {linked_list}")
print(f"Reverse List: {in_reverse(linked_list)}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fuzzy_logic/fuzzy_operations.py | fuzzy_logic/fuzzy_operations.py | """
By @Shreya123714
https://en.wikipedia.org/wiki/Fuzzy_set
"""
from __future__ import annotations
from dataclasses import dataclass
import matplotlib.pyplot as plt
import numpy as np
@dataclass
class FuzzySet:
"""
A class for representing and manipulating triangular fuzzy sets.
Attributes:
name: The name or label of the fuzzy set.
left_boundary: The left boundary of the fuzzy set.
peak: The peak (central) value of the fuzzy set.
right_boundary: The right boundary of the fuzzy set.
Methods:
membership(x): Calculate the membership value of an input 'x' in the fuzzy set.
union(other): Calculate the union of this fuzzy set with another fuzzy set.
intersection(other): Calculate the intersection of this fuzzy set with another.
complement(): Calculate the complement (negation) of this fuzzy set.
plot(): Plot the membership function of the fuzzy set.
>>> sheru = FuzzySet("Sheru", 0.4, 1, 0.6)
>>> sheru
FuzzySet(name='Sheru', left_boundary=0.4, peak=1, right_boundary=0.6)
>>> str(sheru)
'Sheru: [0.4, 1, 0.6]'
>>> siya = FuzzySet("Siya", 0.5, 1, 0.7)
>>> siya
FuzzySet(name='Siya', left_boundary=0.5, peak=1, right_boundary=0.7)
# Complement Operation
>>> sheru.complement()
FuzzySet(name='¬Sheru', left_boundary=0.4, peak=0.6, right_boundary=0)
>>> siya.complement() # doctest: +NORMALIZE_WHITESPACE
FuzzySet(name='¬Siya', left_boundary=0.30000000000000004, peak=0.5,
right_boundary=0)
# Intersection Operation
>>> siya.intersection(sheru)
FuzzySet(name='Siya ∩ Sheru', left_boundary=0.5, peak=0.6, right_boundary=1.0)
# Membership Operation
>>> sheru.membership(0.5)
0.16666666666666663
>>> sheru.membership(0.6)
0.0
# Union Operations
>>> siya.union(sheru)
FuzzySet(name='Siya U Sheru', left_boundary=0.4, peak=0.7, right_boundary=1.0)
"""
name: str
left_boundary: float
peak: float
right_boundary: float
def __str__(self) -> str:
"""
>>> FuzzySet("fuzzy_set", 0.1, 0.2, 0.3)
FuzzySet(name='fuzzy_set', left_boundary=0.1, peak=0.2, right_boundary=0.3)
"""
return (
f"{self.name}: [{self.left_boundary}, {self.peak}, {self.right_boundary}]"
)
def complement(self) -> FuzzySet:
"""
Calculate the complement (negation) of this fuzzy set.
Returns:
FuzzySet: A new fuzzy set representing the complement.
>>> FuzzySet("fuzzy_set", 0.1, 0.2, 0.3).complement()
FuzzySet(name='¬fuzzy_set', left_boundary=0.7, peak=0.9, right_boundary=0.8)
"""
return FuzzySet(
f"¬{self.name}",
1 - self.right_boundary,
1 - self.left_boundary,
1 - self.peak,
)
def intersection(self, other) -> FuzzySet:
"""
Calculate the intersection of this fuzzy set
with another fuzzy set.
Args:
other: Another fuzzy set to intersect with.
Returns:
A new fuzzy set representing the intersection.
>>> FuzzySet("a", 0.1, 0.2, 0.3).intersection(FuzzySet("b", 0.4, 0.5, 0.6))
FuzzySet(name='a ∩ b', left_boundary=0.4, peak=0.3, right_boundary=0.35)
"""
return FuzzySet(
f"{self.name} ∩ {other.name}",
max(self.left_boundary, other.left_boundary),
min(self.right_boundary, other.right_boundary),
(self.peak + other.peak) / 2,
)
def membership(self, x: float) -> float:
"""
Calculate the membership value of an input 'x' in the fuzzy set.
Returns:
The membership value of 'x' in the fuzzy set.
>>> a = FuzzySet("a", 0.1, 0.2, 0.3)
>>> a.membership(0.09)
0.0
>>> a.membership(0.1)
0.0
>>> a.membership(0.11)
0.09999999999999995
>>> a.membership(0.4)
0.0
>>> FuzzySet("A", 0, 0.5, 1).membership(0.1)
0.2
>>> FuzzySet("B", 0.2, 0.7, 1).membership(0.6)
0.8
"""
if x <= self.left_boundary or x >= self.right_boundary:
return 0.0
elif self.left_boundary < x <= self.peak:
return (x - self.left_boundary) / (self.peak - self.left_boundary)
elif self.peak < x < self.right_boundary:
return (self.right_boundary - x) / (self.right_boundary - self.peak)
msg = f"Invalid value {x} for fuzzy set {self}"
raise ValueError(msg)
def union(self, other) -> FuzzySet:
"""
Calculate the union of this fuzzy set with another fuzzy set.
Args:
other (FuzzySet): Another fuzzy set to union with.
Returns:
FuzzySet: A new fuzzy set representing the union.
>>> FuzzySet("a", 0.1, 0.2, 0.3).union(FuzzySet("b", 0.4, 0.5, 0.6))
FuzzySet(name='a U b', left_boundary=0.1, peak=0.6, right_boundary=0.35)
"""
return FuzzySet(
f"{self.name} U {other.name}",
min(self.left_boundary, other.left_boundary),
max(self.right_boundary, other.right_boundary),
(self.peak + other.peak) / 2,
)
def plot(self):
"""
Plot the membership function of the fuzzy set.
"""
x = np.linspace(0, 1, 1000)
y = [self.membership(xi) for xi in x]
plt.plot(x, y, label=self.name)
if __name__ == "__main__":
from doctest import testmod
testmod()
a = FuzzySet("A", 0, 0.5, 1)
b = FuzzySet("B", 0.2, 0.7, 1)
a.plot()
b.plot()
plt.xlabel("x")
plt.ylabel("Membership")
plt.legend()
plt.show()
union_ab = a.union(b)
intersection_ab = a.intersection(b)
complement_a = a.complement()
union_ab.plot()
intersection_ab.plot()
complement_a.plot()
plt.xlabel("x")
plt.ylabel("Membership")
plt.legend()
plt.show()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fuzzy_logic/__init__.py | fuzzy_logic/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/sentinel_linear_search.py | searches/sentinel_linear_search.py | """
This is pure Python implementation of sentinel linear search algorithm
For doctests run following command:
python -m doctest -v sentinel_linear_search.py
or
python3 -m doctest -v sentinel_linear_search.py
For manual testing run:
python sentinel_linear_search.py
"""
def sentinel_linear_search(sequence, target):
"""Pure implementation of sentinel linear search algorithm in Python
:param sequence: some sequence with comparable items
:param target: item value to search
:return: index of found item or None if item is not found
Examples:
>>> sentinel_linear_search([0, 5, 7, 10, 15], 0)
0
>>> sentinel_linear_search([0, 5, 7, 10, 15], 15)
4
>>> sentinel_linear_search([0, 5, 7, 10, 15], 5)
1
>>> sentinel_linear_search([0, 5, 7, 10, 15], 6)
"""
sequence.append(target)
index = 0
while sequence[index] != target:
index += 1
sequence.pop()
if index == len(sequence):
return None
return index
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item) for item in user_input.split(",")]
target_input = input("Enter a single number to be found in the list:\n")
target = int(target_input)
result = sentinel_linear_search(sequence, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/simulated_annealing.py | searches/simulated_annealing.py | # https://en.wikipedia.org/wiki/Simulated_annealing
import math
import random
from typing import Any
from .hill_climbing import SearchProblem
def simulated_annealing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
start_temperate: float = 100,
rate_of_decrease: float = 0.01,
threshold_temp: float = 1,
) -> Any:
"""
Implementation of the simulated annealing algorithm. We start with a given state,
find all its neighbors. Pick a random neighbor, if that neighbor improves the
solution, we move in that direction, if that neighbor does not improve the solution,
we generate a random real number between 0 and 1, if the number is within a certain
range (calculated using temperature) we move in that direction, else we pick
another neighbor randomly and repeat the process.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the minimum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
start_temperate: the initial temperate of the system when the program starts.
rate_of_decrease: the rate at which the temperate decreases in each iteration.
threshold_temp: the threshold temperature below which we end the search
Returns a search state having the maximum (or minimum) score.
"""
search_end = False
current_state = search_prob
current_temp = start_temperate
scores = []
iterations = 0
best_state = None
while not search_end:
current_score = current_state.score()
if best_state is None or current_score > best_state.score():
best_state = current_state
scores.append(current_score)
iterations += 1
next_state = None
neighbors = current_state.get_neighbors()
while (
next_state is None and neighbors
): # till we do not find a neighbor that we can move to
index = random.randint(0, len(neighbors) - 1) # picking a random neighbor
picked_neighbor = neighbors.pop(index)
change = picked_neighbor.score() - current_score
if (
picked_neighbor.x > max_x
or picked_neighbor.x < min_x
or picked_neighbor.y > max_y
or picked_neighbor.y < min_y
):
continue # neighbor outside our bounds
if not find_max:
change = change * -1 # in case we are finding minimum
if change > 0: # improves the solution
next_state = picked_neighbor
else:
probability = (math.e) ** (
change / current_temp
) # probability generation function
if random.random() < probability: # random number within probability
next_state = picked_neighbor
current_temp = current_temp - (current_temp * rate_of_decrease)
if current_temp < threshold_temp or next_state is None:
# temperature below threshold, or could not find a suitable neighbor
search_end = True
else:
current_state = next_state
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return best_state
if __name__ == "__main__":
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(
prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=False, visualization=True)
print(
"The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=True, visualization=True)
print(
"The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: "
f"{local_min.score()}"
)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/hill_climbing.py | searches/hill_climbing.py | # https://en.wikipedia.org/wiki/Hill_climbing
import math
class SearchProblem:
"""
An interface to define search problems.
The interface will be illustrated using the example of mathematical function.
"""
def __init__(self, x: int, y: int, step_size: int, function_to_optimize):
"""
The constructor of the search problem.
x: the x coordinate of the current search state.
y: the y coordinate of the current search state.
step_size: size of the step to take when looking for neighbors.
function_to_optimize: a function to optimize having the signature f(x, y).
"""
self.x = x
self.y = y
self.step_size = step_size
self.function = function_to_optimize
def score(self) -> int:
"""
Returns the output of the function called with current x and y coordinates.
>>> def test_function(x, y):
... return x + y
>>> SearchProblem(0, 0, 1, test_function).score() # 0 + 0 = 0
0
>>> SearchProblem(5, 7, 1, test_function).score() # 5 + 7 = 12
12
"""
return self.function(self.x, self.y)
def get_neighbors(self):
"""
Returns a list of coordinates of neighbors adjacent to the current coordinates.
Neighbors:
| 0 | 1 | 2 |
| 3 | _ | 4 |
| 5 | 6 | 7 |
"""
step_size = self.step_size
return [
SearchProblem(x, y, step_size, self.function)
for x, y in (
(self.x - step_size, self.y - step_size),
(self.x - step_size, self.y),
(self.x - step_size, self.y + step_size),
(self.x, self.y - step_size),
(self.x, self.y + step_size),
(self.x + step_size, self.y - step_size),
(self.x + step_size, self.y),
(self.x + step_size, self.y + step_size),
)
]
def __hash__(self):
"""
hash the string representation of the current search state.
"""
return hash(str(self))
def __eq__(self, obj):
"""
Check if the 2 objects are equal.
"""
if isinstance(obj, SearchProblem):
return hash(str(self)) == hash(str(obj))
return False
def __str__(self):
"""
string representation of the current search state.
>>> str(SearchProblem(0, 0, 1, None))
'x: 0 y: 0'
>>> str(SearchProblem(2, 5, 1, None))
'x: 2 y: 5'
"""
return f"x: {self.x} y: {self.y}"
def hill_climbing(
search_prob,
find_max: bool = True,
max_x: float = math.inf,
min_x: float = -math.inf,
max_y: float = math.inf,
min_y: float = -math.inf,
visualization: bool = False,
max_iter: int = 10000,
) -> SearchProblem:
"""
Implementation of the hill climbling algorithm.
We start with a given state, find all its neighbors,
move towards the neighbor which provides the maximum (or minimum) change.
We keep doing this until we are at a state where we do not have any
neighbors which can improve the solution.
Args:
search_prob: The search state at the start.
find_max: If True, the algorithm should find the maximum else the minimum.
max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y.
visualization: If True, a matplotlib graph is displayed.
max_iter: number of times to run the iteration.
Returns a search state having the maximum (or minimum) score.
"""
current_state = search_prob
scores = [] # list to store the current score at each iteration
iterations = 0
solution_found = False
visited = set()
while not solution_found and iterations < max_iter:
visited.add(current_state)
iterations += 1
current_score = current_state.score()
scores.append(current_score)
neighbors = current_state.get_neighbors()
max_change = -math.inf
min_change = math.inf
next_state = None # to hold the next best neighbor
for neighbor in neighbors:
if neighbor in visited:
continue # do not want to visit the same state again
if (
neighbor.x > max_x
or neighbor.x < min_x
or neighbor.y > max_y
or neighbor.y < min_y
):
continue # neighbor outside our bounds
change = neighbor.score() - current_score
if find_max: # finding max
# going to direction with greatest ascent
if change > max_change and change > 0:
max_change = change
next_state = neighbor
elif change < min_change and change < 0: # finding min
# to direction with greatest descent
min_change = change
next_state = neighbor
if next_state is not None:
# we found at least one neighbor which improved the current state
current_state = next_state
else:
# since we have no neighbor that improves the solution we stop the search
solution_found = True
if visualization:
from matplotlib import pyplot as plt
plt.plot(range(iterations), scores)
plt.xlabel("Iterations")
plt.ylabel("Function values")
plt.show()
return current_state
if __name__ == "__main__":
import doctest
doctest.testmod()
def test_f1(x, y):
return (x**2) + (y**2)
# starting the problem with initial coordinates (3, 4)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=False)
print(
"The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
# starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(
prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True
)
print(
"The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 "
f"and 50 > y > - 5 found via hill climbing: {local_min.score()}"
)
def test_f2(x, y):
return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=True)
print(
"The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: "
f"{local_min.score()}"
)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/simple_binary_search.py | searches/simple_binary_search.py | """
Pure Python implementation of a binary search algorithm.
For doctests run following command:
python3 -m doctest -v simple_binary_search.py
For manual testing run:
python3 simple_binary_search.py
"""
from __future__ import annotations
def binary_search(a_list: list[int], item: int) -> bool:
"""
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> binary_search(test_list, 3)
False
>>> binary_search(test_list, 13)
True
>>> binary_search([4, 4, 5, 6, 7], 4)
True
>>> binary_search([4, 4, 5, 6, 7], -10)
False
>>> binary_search([-18, 2], -18)
True
>>> binary_search([5], 5)
True
>>> binary_search(['a', 'c', 'd'], 'c')
True
>>> binary_search(['a', 'c', 'd'], 'f')
False
>>> binary_search([], 1)
False
>>> binary_search([-.1, .1 , .8], .1)
True
>>> binary_search(range(-5000, 5000, 10), 80)
True
>>> binary_search(range(-5000, 5000, 10), 1255)
False
>>> binary_search(range(0, 10000, 5), 2)
False
"""
if len(a_list) == 0:
return False
midpoint = len(a_list) // 2
if a_list[midpoint] == item:
return True
if item < a_list[midpoint]:
return binary_search(a_list[:midpoint], item)
else:
return binary_search(a_list[midpoint + 1 :], item)
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item.strip()) for item in user_input.split(",")]
target = int(input("Enter the number to be found in the list:\n").strip())
not_str = "" if binary_search(sequence, target) else "not "
print(f"{target} was {not_str}found in {sequence}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/quick_select.py | searches/quick_select.py | """
A Python implementation of the quick select algorithm, which is efficient for
calculating the value that would appear in the index of a list if it would be
sorted, even if it is not already sorted
https://en.wikipedia.org/wiki/Quickselect
"""
import random
def _partition(data: list, pivot) -> tuple:
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, greater = [], [], []
for element in data:
if element < pivot:
less.append(element)
elif element > pivot:
greater.append(element)
else:
equal.append(element)
return less, equal, greater
def quick_select(items: list, index: int):
"""
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 5)
54
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 1)
4
>>> quick_select([5, 4, 3, 2], 2)
4
>>> quick_select([3, 5, 7, 10, 2, 12], 3)
7
"""
# index = len(items) // 2 when trying to find the median
# (value of index when items is sorted)
# invalid input
if index >= len(items) or index < 0:
return None
pivot = items[random.randint(0, len(items) - 1)]
count = 0
smaller, equal, larger = _partition(items, pivot)
count = len(equal)
m = len(smaller)
# index is the pivot
if m <= index < m + count:
return pivot
# must be in smaller
elif m > index:
return quick_select(smaller, index)
# must be in larger
else:
return quick_select(larger, index - (m + count))
def median(items: list):
"""
One common application of Quickselect is finding the median, which is
the middle element (or average of the two middle elements) in a sorted dataset.
It works efficiently on unsorted lists by partially sorting the data without
fully sorting the entire list.
>>> median([3, 2, 2, 9, 9])
3
>>> median([2, 2, 9, 9, 9, 3])
6.0
"""
mid, rem = divmod(len(items), 2)
if rem != 0:
return quick_select(items=items, index=mid)
else:
low_mid = quick_select(items=items, index=mid - 1)
high_mid = quick_select(items=items, index=mid)
return (low_mid + high_mid) / 2
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/double_linear_search_recursion.py | searches/double_linear_search_recursion.py | def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int:
"""
Iterate through the array to find the index of key using recursion.
:param list_data: the list to be searched
:param key: the key to be searched
:param left: the index of first element
:param right: the index of last element
:return: the index of key value if found, -1 otherwise.
>>> search(list(range(0, 11)), 5)
5
>>> search([1, 2, 4, 5, 3], 4)
2
>>> search([1, 2, 4, 5, 3], 6)
-1
>>> search([5], 5)
0
>>> search([], 1)
-1
"""
right = right or len(list_data) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(list_data, key, left + 1, right - 1)
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/fibonacci_search.py | searches/fibonacci_search.py | """
This is pure Python implementation of fibonacci search.
Resources used:
https://en.wikipedia.org/wiki/Fibonacci_search_technique
For doctests run following command:
python3 -m doctest -v fibonacci_search.py
For manual testing run:
python3 fibonacci_search.py
"""
from functools import lru_cache
@lru_cache
def fibonacci(k: int) -> int:
"""Finds fibonacci number in index k.
Parameters
----------
k :
Index of fibonacci.
Returns
-------
int
Fibonacci number in position k.
>>> fibonacci(0)
0
>>> fibonacci(2)
1
>>> fibonacci(5)
5
>>> fibonacci(15)
610
>>> fibonacci('a')
Traceback (most recent call last):
TypeError: k must be an integer.
>>> fibonacci(-5)
Traceback (most recent call last):
ValueError: k integer must be greater or equal to zero.
"""
if not isinstance(k, int):
raise TypeError("k must be an integer.")
if k < 0:
raise ValueError("k integer must be greater or equal to zero.")
if k == 0:
return 0
elif k == 1:
return 1
else:
return fibonacci(k - 1) + fibonacci(k - 2)
def fibonacci_search(arr: list, val: int) -> int:
"""A pure Python implementation of a fibonacci search algorithm.
Parameters
----------
arr
List of sorted elements.
val
Element to search in list.
Returns
-------
int
The index of the element in the array.
-1 if the element is not found.
>>> fibonacci_search([4, 5, 6, 7], 4)
0
>>> fibonacci_search([4, 5, 6, 7], -10)
-1
>>> fibonacci_search([-18, 2], -18)
0
>>> fibonacci_search([5], 5)
0
>>> fibonacci_search(['a', 'c', 'd'], 'c')
1
>>> fibonacci_search(['a', 'c', 'd'], 'f')
-1
>>> fibonacci_search([], 1)
-1
>>> fibonacci_search([.1, .4 , 7], .4)
1
>>> fibonacci_search([], 9)
-1
>>> fibonacci_search(list(range(100)), 63)
63
>>> fibonacci_search(list(range(100)), 99)
99
>>> fibonacci_search(list(range(-100, 100, 3)), -97)
1
>>> fibonacci_search(list(range(-100, 100, 3)), 0)
-1
>>> fibonacci_search(list(range(-100, 100, 5)), 0)
20
>>> fibonacci_search(list(range(-100, 100, 5)), 95)
39
"""
len_list = len(arr)
# Find m such that F_m >= n where F_i is the i_th fibonacci number.
i = 0
while True:
if fibonacci(i) >= len_list:
fibb_k = i
break
i += 1
offset = 0
while fibb_k > 0:
index_k = min(
offset + fibonacci(fibb_k - 1), len_list - 1
) # Prevent out of range
item_k_1 = arr[index_k]
if item_k_1 == val:
return index_k
elif val < item_k_1:
fibb_k -= 1
elif val > item_k_1:
offset += fibonacci(fibb_k - 1)
fibb_k -= 2
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/double_linear_search.py | searches/double_linear_search.py | from __future__ import annotations
def double_linear_search(array: list[int], search_item: int) -> int:
"""
Iterate through the array from both sides to find the index of search_item.
:param array: the array to be searched
:param search_item: the item to be searched
:return the index of search_item, if search_item is in array, else -1
Examples:
>>> double_linear_search([1, 5, 5, 10], 1)
0
>>> double_linear_search([1, 5, 5, 10], 5)
1
>>> double_linear_search([1, 5, 5, 10], 100)
-1
>>> double_linear_search([1, 5, 5, 10], 10)
3
"""
# define the start and end index of the given array
start_ind, end_ind = 0, len(array) - 1
while start_ind <= end_ind:
if array[start_ind] == search_item:
return start_ind
elif array[end_ind] == search_item:
return end_ind
else:
start_ind += 1
end_ind -= 1
# returns -1 if search_item is not found in array
return -1
if __name__ == "__main__":
print(double_linear_search(list(range(100)), 40))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/ternary_search.py | searches/ternary_search.py | """
This is a type of divide and conquer algorithm which divides the search space into
3 parts and finds the target value based on the property of the array or list
(usually monotonic property).
Time Complexity : O(log3 N)
Space Complexity : O(1)
"""
from __future__ import annotations
# This is the precision for this function which can be altered.
# It is recommended for users to keep this number greater than or equal to 10.
precision = 10
# This is the linear search that will occur after the search space has become smaller.
def lin_search(left: int, right: int, array: list[int], target: int) -> int:
"""Perform linear search in list. Returns -1 if element is not found.
Parameters
----------
left : int
left index bound.
right : int
right index bound.
array : List[int]
List of elements to be searched on
target : int
Element that is searched
Returns
-------
int
index of element that is looked for.
Examples
--------
>>> lin_search(0, 4, [4, 5, 6, 7], 7)
3
>>> lin_search(0, 3, [4, 5, 6, 7], 7)
-1
>>> lin_search(0, 2, [-18, 2], -18)
0
>>> lin_search(0, 1, [5], 5)
0
>>> lin_search(0, 3, ['a', 'c', 'd'], 'c')
1
>>> lin_search(0, 3, [.1, .4 , -.1], .1)
0
>>> lin_search(0, 3, [.1, .4 , -.1], -.1)
2
"""
for i in range(left, right):
if array[i] == target:
return i
return -1
def ite_ternary_search(array: list[int], target: int) -> int:
"""Iterative method of the ternary search algorithm.
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> ite_ternary_search(test_list, 3)
-1
>>> ite_ternary_search(test_list, 13)
4
>>> ite_ternary_search([4, 5, 6, 7], 4)
0
>>> ite_ternary_search([4, 5, 6, 7], -10)
-1
>>> ite_ternary_search([-18, 2], -18)
0
>>> ite_ternary_search([5], 5)
0
>>> ite_ternary_search(['a', 'c', 'd'], 'c')
1
>>> ite_ternary_search(['a', 'c', 'd'], 'f')
-1
>>> ite_ternary_search([], 1)
-1
>>> ite_ternary_search([.1, .4 , -.1], .1)
0
"""
left = 0
right = len(array)
while left <= right:
if right - left < precision:
return lin_search(left, right, array, target)
one_third = (left + right) // 3 + 1
two_third = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
right = one_third - 1
elif array[two_third] < target:
left = two_third + 1
else:
left = one_third + 1
right = two_third - 1
return -1
def rec_ternary_search(left: int, right: int, array: list[int], target: int) -> int:
"""Recursive method of the ternary search algorithm.
>>> test_list = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> rec_ternary_search(0, len(test_list), test_list, 3)
-1
>>> rec_ternary_search(4, len(test_list), test_list, 42)
8
>>> rec_ternary_search(0, 2, [4, 5, 6, 7], 4)
0
>>> rec_ternary_search(0, 3, [4, 5, 6, 7], -10)
-1
>>> rec_ternary_search(0, 1, [-18, 2], -18)
0
>>> rec_ternary_search(0, 1, [5], 5)
0
>>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'c')
1
>>> rec_ternary_search(0, 2, ['a', 'c', 'd'], 'f')
-1
>>> rec_ternary_search(0, 0, [], 1)
-1
>>> rec_ternary_search(0, 3, [.1, .4 , -.1], .1)
0
"""
if left < right:
if right - left < precision:
return lin_search(left, right, array, target)
one_third = (left + right) // 3 + 1
two_third = 2 * (left + right) // 3 + 1
if array[one_third] == target:
return one_third
elif array[two_third] == target:
return two_third
elif target < array[one_third]:
return rec_ternary_search(left, one_third - 1, array, target)
elif array[two_third] < target:
return rec_ternary_search(two_third + 1, right, array, target)
else:
return rec_ternary_search(one_third + 1, two_third - 1, array, target)
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
user_input = input("Enter numbers separated by comma:\n").strip()
collection = [int(item.strip()) for item in user_input.split(",")]
assert collection == sorted(collection), f"List must be ordered.\n{collection}."
target = int(input("Enter the number to be found in the list:\n").strip())
result1 = ite_ternary_search(collection, target)
result2 = rec_ternary_search(0, len(collection) - 1, collection, target)
if result2 != -1:
print(f"Iterative search: {target} found at positions: {result1}")
print(f"Recursive search: {target} found at positions: {result2}")
else:
print("Not found")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/median_of_medians.py | searches/median_of_medians.py | """
A Python implementation of the Median of Medians algorithm
to select pivots for quick_select, which is efficient for
calculating the value that would appear in the index of a
list if it would be sorted, even if it is not already
sorted. Search in time complexity O(n) at any rank
deterministically
https://en.wikipedia.org/wiki/Median_of_medians
"""
def median_of_five(arr: list) -> int:
"""
Return the median of the input list
:param arr: Array to find median of
:return: median of arr
>>> median_of_five([2, 4, 5, 7, 899])
5
>>> median_of_five([5, 7, 899, 54, 32])
32
>>> median_of_five([5, 4, 3, 2])
4
>>> median_of_five([3, 5, 7, 10, 2])
5
"""
arr = sorted(arr)
return arr[len(arr) // 2]
def median_of_medians(arr: list) -> int:
"""
Return a pivot to partition data on by calculating
Median of medians of input data
:param arr: The data to be checked (a list)
:return: median of medians of input array
>>> median_of_medians([2, 4, 5, 7, 899, 54, 32])
54
>>> median_of_medians([5, 7, 899, 54, 32])
32
>>> median_of_medians([5, 4, 3, 2])
4
>>> median_of_medians([3, 5, 7, 10, 2, 12])
12
"""
if len(arr) <= 5:
return median_of_five(arr)
medians = []
i = 0
while i < len(arr):
if (i + 4) <= len(arr):
medians.append(median_of_five(arr[i:].copy()))
else:
medians.append(median_of_five(arr[i : i + 5].copy()))
i += 5
return median_of_medians(medians)
def quick_select(arr: list, target: int) -> int:
"""
Two way partition the data into smaller and greater lists,
in relationship to the pivot
:param arr: The data to be searched (a list)
:param target: The rank to be searched
:return: element at rank target
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 5)
32
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 1)
2
>>> quick_select([5, 4, 3, 2], 2)
3
>>> quick_select([3, 5, 7, 10, 2, 12], 3)
5
"""
# Invalid Input
if target > len(arr):
return -1
# x is the estimated pivot by median of medians algorithm
x = median_of_medians(arr)
left = []
right = []
check = False
for i in range(len(arr)):
if arr[i] < x:
left.append(arr[i])
elif arr[i] > x:
right.append(arr[i])
elif arr[i] == x and not check:
check = True
else:
right.append(arr[i])
rank_x = len(left) + 1
if rank_x == target:
answer = x
elif rank_x > target:
answer = quick_select(left, target)
elif rank_x < target:
answer = quick_select(right, target - rank_x)
return answer
print(median_of_five([5, 4, 3, 2]))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/exponential_search.py | searches/exponential_search.py | #!/usr/bin/env python3
"""
Pure Python implementation of exponential search algorithm
For more information, see the Wikipedia page:
https://en.wikipedia.org/wiki/Exponential_search
For doctests run the following command:
python3 -m doctest -v exponential_search.py
For manual testing run:
python3 exponential_search.py
"""
from __future__ import annotations
def binary_search_by_recursion(
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
) -> int:
"""Pure implementation of binary search algorithm in Python using recursion
Be careful: the collection must be ascending sorted otherwise, the result will be
unpredictable.
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:param left: starting index for the search
:param right: ending index for the search
:return: index of the found item or -1 if the item is not found
Examples:
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
0
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
4
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
1
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
-1
"""
if right < 0:
right = len(sorted_collection) - 1
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
if right < left:
return -1
midpoint = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
else:
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
def exponential_search(sorted_collection: list[int], item: int) -> int:
"""
Pure implementation of an exponential search algorithm in Python.
For more information, refer to:
https://en.wikipedia.org/wiki/Exponential_search
Be careful: the collection must be ascending sorted, otherwise the result will be
unpredictable.
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
The time complexity of this algorithm is O(log i) where i is the index of the item.
Examples:
>>> exponential_search([0, 5, 7, 10, 15], 0)
0
>>> exponential_search([0, 5, 7, 10, 15], 15)
4
>>> exponential_search([0, 5, 7, 10, 15], 5)
1
>>> exponential_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
if sorted_collection[0] == item:
return 0
bound = 1
while bound < len(sorted_collection) and sorted_collection[bound] < item:
bound *= 2
left = bound // 2
right = min(bound, len(sorted_collection) - 1)
return binary_search_by_recursion(sorted_collection, item, left, right)
if __name__ == "__main__":
import doctest
doctest.testmod()
# Manual testing
user_input = input("Enter numbers separated by commas: ").strip()
collection = sorted(int(item) for item in user_input.split(","))
target = int(input("Enter a number to search for: "))
result = exponential_search(sorted_collection=collection, item=target)
if result == -1:
print(f"{target} was not found in {collection}.")
else:
print(f"{target} was found at index {result} in {collection}.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/jump_search.py | searches/jump_search.py | """
Pure Python implementation of the jump search algorithm.
This algorithm iterates through a sorted collection with a step of n^(1/2),
until the element compared is bigger than the one searched.
It will then perform a linear search until it matches the wanted number.
If not found, it returns -1.
https://en.wikipedia.org/wiki/Jump_search
"""
import math
from collections.abc import Sequence
from typing import Any, Protocol, TypeVar
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
T = TypeVar("T", bound=Comparable)
def jump_search(arr: Sequence[T], item: T) -> int:
"""
Python implementation of the jump search algorithm.
Return the index if the `item` is found, otherwise return -1.
Examples:
>>> jump_search([0, 1, 2, 3, 4, 5], 3)
3
>>> jump_search([-5, -2, -1], -1)
2
>>> jump_search([0, 5, 10, 20], 8)
-1
>>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55)
10
>>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee")
4
"""
arr_size = len(arr)
block_size = int(math.sqrt(arr_size))
prev = 0
step = block_size
while arr[min(step, arr_size) - 1] < item:
prev = step
step += block_size
if prev >= arr_size:
return -1
while arr[prev] < item:
prev += 1
if prev == min(step, arr_size):
return -1
if arr[prev] == item:
return prev
return -1
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
array = [int(item) for item in user_input.split(",")]
x = int(input("Enter the number to be searched:\n"))
res = jump_search(array, x)
if res == -1:
print("Number not found!")
else:
print(f"Number {x} is at index {res}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/__init__.py | searches/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/linear_search.py | searches/linear_search.py | """
This is pure Python implementation of linear search algorithm
For doctests run following command:
python3 -m doctest -v linear_search.py
For manual testing run:
python3 linear_search.py
"""
def linear_search(sequence: list, target: int) -> int:
"""A pure Python implementation of a linear search algorithm
:param sequence: a collection with comparable items (as sorted items not required
in Linear Search)
:param target: item value to search
:return: index of found item or -1 if item is not found
Examples:
>>> linear_search([0, 5, 7, 10, 15], 0)
0
>>> linear_search([0, 5, 7, 10, 15], 15)
4
>>> linear_search([0, 5, 7, 10, 15], 5)
1
>>> linear_search([0, 5, 7, 10, 15], 6)
-1
"""
for index, item in enumerate(sequence):
if item == target:
return index
return -1
def rec_linear_search(sequence: list, low: int, high: int, target: int) -> int:
"""
A pure Python implementation of a recursive linear search algorithm
:param sequence: a collection with comparable items (as sorted items not required
in Linear Search)
:param low: Lower bound of the array
:param high: Higher bound of the array
:param target: The element to be found
:return: Index of the key or -1 if key not found
Examples:
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 0)
0
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 700)
4
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, 30)
1
>>> rec_linear_search([0, 30, 500, 100, 700], 0, 4, -6)
-1
"""
if not (0 <= high < len(sequence) and 0 <= low < len(sequence)):
raise Exception("Invalid upper or lower bound!")
if high < low:
return -1
if sequence[low] == target:
return low
if sequence[high] == target:
return high
return rec_linear_search(sequence, low + 1, high - 1, target)
if __name__ == "__main__":
user_input = input("Enter numbers separated by comma:\n").strip()
sequence = [int(item.strip()) for item in user_input.split(",")]
target = int(input("Enter a single number to be found in the list:\n").strip())
result = linear_search(sequence, target)
if result != -1:
print(f"linear_search({sequence}, {target}) = {result}")
else:
print(f"{target} was not found in {sequence}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/binary_search.py | searches/binary_search.py | #!/usr/bin/env python3
"""
Pure Python implementations of binary search algorithms
For doctests run the following command:
python3 -m doctest -v binary_search.py
For manual testing run:
python3 binary_search.py
"""
from __future__ import annotations
import bisect
def bisect_left(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> int:
"""
Locates the first element in a sorted array that is larger or equal to a given
value.
It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.bisect_left .
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item to bisect
:param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi])
:return: index i such that all values in sorted_collection[lo:i] are < item and all
values in sorted_collection[i:hi] are >= item.
Examples:
>>> bisect_left([0, 5, 7, 10, 15], 0)
0
>>> bisect_left([0, 5, 7, 10, 15], 6)
2
>>> bisect_left([0, 5, 7, 10, 15], 20)
5
>>> bisect_left([0, 5, 7, 10, 15], 15, 1, 3)
3
>>> bisect_left([0, 5, 7, 10, 15], 6, 2)
2
"""
if hi < 0:
hi = len(sorted_collection)
while lo < hi:
mid = lo + (hi - lo) // 2
if sorted_collection[mid] < item:
lo = mid + 1
else:
hi = mid
return lo
def bisect_right(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> int:
"""
Locates the first element in a sorted array that is larger than a given value.
It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.bisect_right .
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item to bisect
:param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi])
:return: index i such that all values in sorted_collection[lo:i] are <= item and
all values in sorted_collection[i:hi] are > item.
Examples:
>>> bisect_right([0, 5, 7, 10, 15], 0)
1
>>> bisect_right([0, 5, 7, 10, 15], 15)
5
>>> bisect_right([0, 5, 7, 10, 15], 6)
2
>>> bisect_right([0, 5, 7, 10, 15], 15, 1, 3)
3
>>> bisect_right([0, 5, 7, 10, 15], 6, 2)
2
"""
if hi < 0:
hi = len(sorted_collection)
while lo < hi:
mid = lo + (hi - lo) // 2
if sorted_collection[mid] <= item:
lo = mid + 1
else:
hi = mid
return lo
def insort_left(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> None:
"""
Inserts a given value into a sorted array before other values with the same value.
It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.insort_left .
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item to insert
:param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi])
Examples:
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_left(sorted_collection, 6)
>>> sorted_collection
[0, 5, 6, 7, 10, 15]
>>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)]
>>> item = (5, 5)
>>> insort_left(sorted_collection, item)
>>> sorted_collection
[(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)]
>>> item is sorted_collection[1]
True
>>> item is sorted_collection[2]
False
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_left(sorted_collection, 20)
>>> sorted_collection
[0, 5, 7, 10, 15, 20]
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_left(sorted_collection, 15, 1, 3)
>>> sorted_collection
[0, 5, 7, 15, 10, 15]
"""
sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item)
def insort_right(
sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1
) -> None:
"""
Inserts a given value into a sorted array after other values with the same value.
It has the same interface as
https://docs.python.org/3/library/bisect.html#bisect.insort_right .
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item to insert
:param lo: lowest index to consider (as in sorted_collection[lo:hi])
:param hi: past the highest index to consider (as in sorted_collection[lo:hi])
Examples:
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_right(sorted_collection, 6)
>>> sorted_collection
[0, 5, 6, 7, 10, 15]
>>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)]
>>> item = (5, 5)
>>> insort_right(sorted_collection, item)
>>> sorted_collection
[(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)]
>>> item is sorted_collection[1]
False
>>> item is sorted_collection[2]
True
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_right(sorted_collection, 20)
>>> sorted_collection
[0, 5, 7, 10, 15, 20]
>>> sorted_collection = [0, 5, 7, 10, 15]
>>> insort_right(sorted_collection, 15, 1, 3)
>>> sorted_collection
[0, 5, 7, 15, 10, 15]
"""
sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item)
def binary_search(sorted_collection: list[int], item: int) -> int:
"""Pure implementation of a binary search algorithm in Python
Be careful collection must be ascending sorted otherwise, the result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
Examples:
>>> binary_search([0, 5, 7, 10, 15], 0)
0
>>> binary_search([0, 5, 7, 10, 15], 15)
4
>>> binary_search([0, 5, 7, 10, 15], 5)
1
>>> binary_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
left = 0
right = len(sorted_collection) - 1
while left <= right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item == item:
return midpoint
elif item < current_item:
right = midpoint - 1
else:
left = midpoint + 1
return -1
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:
"""Pure implementation of a binary search algorithm in Python using stdlib
Be careful collection must be ascending sorted otherwise, the result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
Examples:
>>> binary_search_std_lib([0, 5, 7, 10, 15], 0)
0
>>> binary_search_std_lib([0, 5, 7, 10, 15], 15)
4
>>> binary_search_std_lib([0, 5, 7, 10, 15], 5)
1
>>> binary_search_std_lib([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
index = bisect.bisect_left(sorted_collection, item)
if index != len(sorted_collection) and sorted_collection[index] == item:
return index
return -1
def binary_search_with_duplicates(sorted_collection: list[int], item: int) -> list[int]:
"""Pure implementation of a binary search algorithm in Python that supports
duplicates.
Resources used:
https://stackoverflow.com/questions/13197552/using-binary-search-with-sorted-array-with-duplicates
The collection must be sorted in ascending order; otherwise the result will be
unpredictable. If the target appears multiple times, this function returns a
list of all indexes where the target occurs. If the target is not found,
this function returns an empty list.
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search for
:return: a list of indexes where the item is found (empty list if not found)
Examples:
>>> binary_search_with_duplicates([0, 5, 7, 10, 15], 0)
[0]
>>> binary_search_with_duplicates([0, 5, 7, 10, 15], 15)
[4]
>>> binary_search_with_duplicates([1, 2, 2, 2, 3], 2)
[1, 2, 3]
>>> binary_search_with_duplicates([1, 2, 2, 2, 3], 4)
[]
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
def lower_bound(sorted_collection: list[int], item: int) -> int:
"""
Returns the index of the first element greater than or equal to the item.
:param sorted_collection: The sorted list to search.
:param item: The item to find the lower bound for.
:return: The index where the item can be inserted while maintaining order.
"""
left = 0
right = len(sorted_collection)
while left < right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item < item:
left = midpoint + 1
else:
right = midpoint
return left
def upper_bound(sorted_collection: list[int], item: int) -> int:
"""
Returns the index of the first element strictly greater than the item.
:param sorted_collection: The sorted list to search.
:param item: The item to find the upper bound for.
:return: The index where the item can be inserted after all existing instances.
"""
left = 0
right = len(sorted_collection)
while left < right:
midpoint = left + (right - left) // 2
current_item = sorted_collection[midpoint]
if current_item <= item:
left = midpoint + 1
else:
right = midpoint
return left
left = lower_bound(sorted_collection, item)
right = upper_bound(sorted_collection, item)
if left == len(sorted_collection) or sorted_collection[left] != item:
return []
return list(range(left, right))
def binary_search_by_recursion(
sorted_collection: list[int], item: int, left: int = 0, right: int = -1
) -> int:
"""Pure implementation of a binary search algorithm in Python by recursion
Be careful collection must be ascending sorted otherwise, the result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
Examples:
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4)
0
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4)
4
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4)
1
>>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4)
-1
"""
if right < 0:
right = len(sorted_collection) - 1
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
if right < left:
return -1
midpoint = left + (right - left) // 2
if sorted_collection[midpoint] == item:
return midpoint
elif sorted_collection[midpoint] > item:
return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1)
else:
return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right)
def exponential_search(sorted_collection: list[int], item: int) -> int:
"""Pure implementation of an exponential search algorithm in Python
Resources used:
https://en.wikipedia.org/wiki/Exponential_search
Be careful collection must be ascending sorted otherwise, result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of the found item or -1 if the item is not found
the order of this algorithm is O(lg I) where I is index position of item if exist
Examples:
>>> exponential_search([0, 5, 7, 10, 15], 0)
0
>>> exponential_search([0, 5, 7, 10, 15], 15)
4
>>> exponential_search([0, 5, 7, 10, 15], 5)
1
>>> exponential_search([0, 5, 7, 10, 15], 6)
-1
"""
if list(sorted_collection) != sorted(sorted_collection):
raise ValueError("sorted_collection must be sorted in ascending order")
bound = 1
while bound < len(sorted_collection) and sorted_collection[bound] < item:
bound *= 2
left = bound // 2
right = min(bound, len(sorted_collection) - 1)
last_result = binary_search_by_recursion(
sorted_collection=sorted_collection, item=item, left=left, right=right
)
if last_result is None:
return -1
return last_result
searches = ( # Fastest to slowest...
binary_search_std_lib,
binary_search,
exponential_search,
binary_search_by_recursion,
)
if __name__ == "__main__":
import doctest
import timeit
doctest.testmod()
for search in searches:
name = f"{search.__name__:>26}"
print(f"{name}: {search([0, 5, 7, 10, 15], 10) = }") # type: ignore[operator]
print("\nBenchmarks...")
setup = "collection = range(1000)"
for search in searches:
name = search.__name__
print(
f"{name:>26}:",
timeit.timeit(
f"{name}(collection, 500)", setup=setup, number=5_000, globals=globals()
),
)
user_input = input("\nEnter numbers separated by comma: ").strip()
collection = sorted(int(item) for item in user_input.split(","))
target = int(input("Enter a single number to be found in the list: "))
result = binary_search(sorted_collection=collection, item=target)
if result == -1:
print(f"{target} was not found in {collection}.")
else:
print(f"{target} was found at position {result} of {collection}.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/interpolation_search.py | searches/interpolation_search.py | """
This is pure Python implementation of interpolation search algorithm
"""
def interpolation_search(sorted_collection: list[int], item: int) -> int | None:
"""
Searches for an item in a sorted collection by interpolation search algorithm.
Args:
sorted_collection: sorted list of integers
item: item value to search
Returns:
int: The index of the found item, or None if the item is not found.
Examples:
>>> interpolation_search([1, 2, 3, 4, 5], 2)
1
>>> interpolation_search([1, 2, 3, 4, 5], 4)
3
>>> interpolation_search([1, 2, 3, 4, 5], 6) is None
True
>>> interpolation_search([], 1) is None
True
>>> interpolation_search([100], 100)
0
>>> interpolation_search([1, 2, 3, 4, 5], 0) is None
True
>>> interpolation_search([1, 2, 3, 4, 5], 7) is None
True
>>> interpolation_search([1, 2, 3, 4, 5], 2)
1
>>> interpolation_search([1, 2, 3, 4, 5], 0) is None
True
>>> interpolation_search([1, 2, 3, 4, 5], 7) is None
True
>>> interpolation_search([1, 2, 3, 4, 5], 2)
1
>>> interpolation_search([5, 5, 5, 5, 5], 3) is None
True
"""
left = 0
right = len(sorted_collection) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
if point < left:
right = left
left = point
elif point > right:
left = right
right = point
elif item < current_item:
right = point - 1
else:
left = point + 1
return None
def interpolation_search_by_recursion(
sorted_collection: list[int], item: int, left: int = 0, right: int | None = None
) -> int | None:
"""Pure implementation of interpolation search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
Args:
sorted_collection: some sorted collection with comparable items
item: item value to search
left: left index in collection
right: right index in collection
Returns:
index of item in collection or None if item is not present
Examples:
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 0)
0
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 15)
4
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 5)
1
>>> interpolation_search_by_recursion([0, 5, 7, 10, 15], 100) is None
True
>>> interpolation_search_by_recursion([5, 5, 5, 5, 5], 3) is None
True
"""
if right is None:
right = len(sorted_collection) - 1
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
if sorted_collection[point] == item:
return point
if point < left:
return interpolation_search_by_recursion(sorted_collection, item, point, left)
if point > right:
return interpolation_search_by_recursion(sorted_collection, item, right, left)
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
sorted_collection, item, left, point - 1
)
return interpolation_search_by_recursion(sorted_collection, item, point + 1, right)
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/tabu_search.py | searches/tabu_search.py | """
This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
Problem, that the distances between the cities are symmetric (the distance between city
'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the
distance between them is represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means
in the .txt file should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
-s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import argparse
import copy
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = []
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = []
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start,
with the redundant resolution strategy. That means that we start from the starting
node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
(let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman
will travel, if he follows the path in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of
each solution from lowest to highest) of a solution with 1-1 exchange method, that
means we exchange each node in a solution with each other node and generating a
number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total
distance of each solution (in form of list) that are produced with 1-1 exchange
from the solution that the method took as an input
Example:
>>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
... ) # doctest: +NORMALIZE_WHITESPACE
[['a', 'e', 'b', 'd', 'c', 'a', 90],
['a', 'c', 'd', 'b', 'e', 'a', 90],
['a', 'd', 'b', 'c', 'e', 'a', 93],
['a', 'c', 'b', 'e', 'd', 'a', 102],
['a', 'c', 'e', 'd', 'b', 'a', 113],
['a', 'b', 'c', 'd', 'e', 'a', 119]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
index_of_last_item_in_the_list = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[index_of_last_item_in_the_list])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
Python.
:param first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will
travel, if he follows the path in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occurred
during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he
follows the path in best_solution ever.
"""
count = 1
solution = first_solution
tabu_list = []
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/searches/binary_tree_traversal.py | searches/binary_tree_traversal.py | """
This is pure Python implementation of tree traversal algorithms
"""
from __future__ import annotations
import queue
class TreeNode:
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def build_tree() -> TreeNode:
print("\n********Press N to stop entering at any point of time********\n")
check = input("Enter the value of the root node: ").strip().lower()
q: queue.Queue = queue.Queue()
tree_node = TreeNode(int(check))
q.put(tree_node)
while not q.empty():
node_found = q.get()
msg = f"Enter the left node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
left_node = TreeNode(int(check))
node_found.left = left_node
q.put(left_node)
msg = f"Enter the right node of {node_found.data}: "
check = input(msg).strip().lower() or "n"
if check == "n":
return tree_node
right_node = TreeNode(int(check))
node_found.right = right_node
q.put(right_node)
raise ValueError("Something went wrong")
def pre_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
print(node.data, end=",")
pre_order(node.left)
pre_order(node.right)
def in_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
in_order(node.left)
print(node.data, end=",")
in_order(node.right)
def post_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
post_order(node.left)
post_order(node.right)
print(node.data, end=",")
def level_order(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order(root)
1,2,3,4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
q.put(node_dequeued.left)
if node_dequeued.right:
q.put(node_dequeued.right)
def level_order_actual(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> level_order_actual(root)
1,
2,3,
4,5,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
q: queue.Queue = queue.Queue()
q.put(node)
while not q.empty():
list_ = []
while not q.empty():
node_dequeued = q.get()
print(node_dequeued.data, end=",")
if node_dequeued.left:
list_.append(node_dequeued.left)
if node_dequeued.right:
list_.append(node_dequeued.right)
print()
for inner_node in list_:
q.put(inner_node)
# iteration version
def pre_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> pre_order_iter(root)
1,2,4,5,3,6,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n: # start from root node, find its left child
print(n.data, end=",")
stack.append(n)
n = n.left
# end of while means current node doesn't have left child
n = stack.pop()
# start to traverse its right child
n = n.right
def in_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> in_order_iter(root)
4,2,5,1,6,3,7,
"""
if not isinstance(node, TreeNode) or not node:
return
stack: list[TreeNode] = []
n = node
while n or stack:
while n:
stack.append(n)
n = n.left
n = stack.pop()
print(n.data, end=",")
n = n.right
def post_order_iter(node: TreeNode) -> None:
"""
>>> root = TreeNode(1)
>>> tree_node2 = TreeNode(2)
>>> tree_node3 = TreeNode(3)
>>> tree_node4 = TreeNode(4)
>>> tree_node5 = TreeNode(5)
>>> tree_node6 = TreeNode(6)
>>> tree_node7 = TreeNode(7)
>>> root.left, root.right = tree_node2, tree_node3
>>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5
>>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7
>>> post_order_iter(root)
4,5,2,6,7,3,1,
"""
if not isinstance(node, TreeNode) or not node:
return
stack1, stack2 = [], []
n = node
stack1.append(n)
while stack1: # to find the reversed order of post order, store it in stack2
n = stack1.pop()
if n.left:
stack1.append(n.left)
if n.right:
stack1.append(n.right)
stack2.append(n)
while stack2: # pop up from stack2 will be the post order
print(stack2.pop().data, end=",")
def prompt(s: str = "", width=50, char="*") -> str:
if not s:
return "\n" + width * char
left, extra = divmod(width - len(s) - 2, 2)
return f"{left * char} {s} {(left + extra) * char}"
if __name__ == "__main__":
import doctest
doctest.testmod()
print(prompt("Binary Tree Traversals"))
node: TreeNode = build_tree()
print(prompt("Pre Order Traversal"))
pre_order(node)
print(prompt() + "\n")
print(prompt("In Order Traversal"))
in_order(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal"))
post_order(node)
print(prompt() + "\n")
print(prompt("Level Order Traversal"))
level_order(node)
print(prompt() + "\n")
print(prompt("Actual Level Order Traversal"))
level_order_actual(node)
print("*" * 50 + "\n")
print(prompt("Pre Order Traversal - Iteration Version"))
pre_order_iter(node)
print(prompt() + "\n")
print(prompt("In Order Traversal - Iteration Version"))
in_order_iter(node)
print(prompt() + "\n")
print(prompt("Post Order Traversal - Iteration Version"))
post_order_iter(node)
print(prompt())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/least_recently_used.py | other/least_recently_used.py | from __future__ import annotations
import sys
from collections import deque
from typing import TypeVar
T = TypeVar("T")
class LRUCache[T]:
"""
Page Replacement Algorithm, Least Recently Used (LRU) Caching.
>>> lru_cache: LRUCache[str | int] = LRUCache(4)
>>> lru_cache.refer("A")
>>> lru_cache.refer(2)
>>> lru_cache.refer(3)
>>> lru_cache
LRUCache(4) => [3, 2, 'A']
>>> lru_cache.refer("A")
>>> lru_cache
LRUCache(4) => ['A', 3, 2]
>>> lru_cache.refer(4)
>>> lru_cache.refer(5)
>>> lru_cache
LRUCache(4) => [5, 4, 'A', 3]
"""
dq_store: deque[T] # Cache store of keys
key_reference: set[T] # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
def __init__(self, n: int) -> None:
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference = set()
if not n:
LRUCache._MAX_CAPACITY = sys.maxsize
elif n < 0:
raise ValueError("n should be an integer greater than 0.")
else:
LRUCache._MAX_CAPACITY = n
def refer(self, x: T) -> None:
"""
Looks for a page in the cache store and adds reference to the set.
Remove the least recently used key if the store is full.
Update store to reflect recent access.
"""
if x not in self.key_reference:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference.remove(last_element)
else:
self.dq_store.remove(x)
self.dq_store.appendleft(x)
self.key_reference.add(x)
def display(self) -> None:
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)
def __repr__(self) -> str:
return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}"
if __name__ == "__main__":
import doctest
doctest.testmod()
lru_cache: LRUCache[str | int] = LRUCache(4)
lru_cache.refer("A")
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer("A")
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
print(lru_cache)
assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/nested_brackets.py | other/nested_brackets.py | """
The nested brackets problem is a problem that determines if a sequence of
brackets are properly nested. A sequence of brackets s is considered properly nested
if any of the following conditions are true:
- s is empty
- s has the form (U) or [U] or {U} where U is a properly nested string
- s has the form VW where V and W are properly nested strings
For example, the string "()()[()]" is properly nested but "[(()]" is not.
The function called is_balanced takes as input a string S which is a sequence of
brackets and returns true if S is nested and false otherwise.
"""
def is_balanced(s: str) -> bool:
"""
>>> is_balanced("")
True
>>> is_balanced("()")
True
>>> is_balanced("[]")
True
>>> is_balanced("{}")
True
>>> is_balanced("()[]{}")
True
>>> is_balanced("(())")
True
>>> is_balanced("[[")
False
>>> is_balanced("([{}])")
True
>>> is_balanced("(()[)]")
False
>>> is_balanced("([)]")
False
>>> is_balanced("[[()]]")
True
>>> is_balanced("(()(()))")
True
>>> is_balanced("]")
False
>>> is_balanced("Life is a bowl of cherries.")
True
>>> is_balanced("Life is a bowl of che{}ies.")
True
>>> is_balanced("Life is a bowl of che}{ies.")
False
"""
open_to_closed = {"{": "}", "[": "]", "(": ")"}
stack = []
for symbol in s:
if symbol in open_to_closed:
stack.append(symbol)
elif symbol in open_to_closed.values() and (
not stack or open_to_closed[stack.pop()] != symbol
):
return False
return not stack # stack should be empty
def main():
s = input("Enter sequence of brackets: ")
print(f"'{s}' is {'' if is_balanced(s) else 'not '}balanced.")
if __name__ == "__main__":
from doctest import testmod
testmod()
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/davis_putnam_logemann_loveland.py | other/davis_putnam_logemann_loveland.py | #!/usr/bin/env python3
"""
Davis-Putnam-Logemann-Loveland (DPLL) algorithm is a complete, backtracking-based
search algorithm for deciding the satisfiability of propositional logic formulae in
conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability
(CNF-SAT) problem.
For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from __future__ import annotations
import random
from collections.abc import Iterable
class Clause:
"""
| A clause represented in Conjunctive Normal Form.
| A clause is a set of literals, either complemented or otherwise.
For example:
* {A1, A2, A3'} is the clause (A1 v A2 v A3')
* {A5', A2', A1} is the clause (A5' v A2' v A1)
Create model
>>> clause = Clause(["A1", "A2'", "A3"])
>>> clause.evaluate({"A1": True})
True
"""
def __init__(self, literals: list[str]) -> None:
"""
Represent the literals and an assignment in a clause."
"""
# Assign all literals to None initially
self.literals: dict[str, bool | None] = dict.fromkeys(literals)
def __str__(self) -> str:
"""
To print a clause as in Conjunctive Normal Form.
>>> str(Clause(["A1", "A2'", "A3"]))
"{A1 , A2' , A3}"
"""
return "{" + " , ".join(self.literals) + "}"
def __len__(self) -> int:
"""
To print a clause as in Conjunctive Normal Form.
>>> len(Clause([]))
0
>>> len(Clause(["A1", "A2'", "A3"]))
3
"""
return len(self.literals)
def assign(self, model: dict[str, bool | None]) -> None:
"""
Assign values to literals of the clause as given by model.
"""
for literal in self.literals:
symbol = literal[:2]
if symbol in model:
value = model[symbol]
else:
continue
# Complement assignment if literal is in complemented form
if value is not None and literal.endswith("'"):
value = not value
self.literals[literal] = value
def evaluate(self, model: dict[str, bool | None]) -> bool | None:
"""
Evaluates the clause with the assignments in model.
This has the following steps:
1. Return ``True`` if both a literal and its complement exist in the clause.
2. Return ``True`` if a single literal has the assignment ``True``.
3. Return ``None`` (unable to complete evaluation)
if a literal has no assignment.
4. Compute disjunction of all values assigned in clause.
"""
for literal in self.literals:
symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'"
if symbol in self.literals:
return True
self.assign(model)
for value in self.literals.values():
if value in (True, None):
return value
return any(self.literals.values())
class Formula:
"""
| A formula represented in Conjunctive Normal Form.
| A formula is a set of clauses.
| For example,
| {{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
"""
def __init__(self, clauses: Iterable[Clause]) -> None:
"""
Represent the number of clauses and the clauses themselves.
"""
self.clauses = list(clauses)
def __str__(self) -> str:
"""
To print a formula as in Conjunctive Normal Form.
>>> str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]))
"{{A1 , A2' , A3} , {A5' , A2' , A1}}"
"""
return "{" + " , ".join(str(clause) for clause in self.clauses) + "}"
def generate_clause() -> Clause:
"""
| Randomly generate a clause.
| All literals have the name Ax, where x is an integer from ``1`` to ``5``.
"""
literals = []
no_of_literals = random.randint(1, 5)
base_var = "A"
i = 0
while i < no_of_literals:
var_no = random.randint(1, 5)
var_name = base_var + str(var_no)
var_complement = random.randint(0, 1)
if var_complement == 1:
var_name += "'"
if var_name in literals:
i -= 1
else:
literals.append(var_name)
i += 1
return Clause(literals)
def generate_formula() -> Formula:
"""
Randomly generate a formula.
"""
clauses: set[Clause] = set()
no_of_clauses = random.randint(1, 10)
while len(clauses) < no_of_clauses:
clauses.add(generate_clause())
return Formula(clauses)
def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]:
"""
| Return the clauses and symbols from a formula.
| A symbol is the uncomplemented form of a literal.
For example,
* Symbol of A3 is A3.
* Symbol of A5' is A5.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> clauses_list = [str(i) for i in clauses]
>>> clauses_list
["{A1 , A2' , A3}", "{A5' , A2' , A1}"]
>>> symbols
['A1', 'A2', 'A3', 'A5']
"""
clauses = formula.clauses
symbols_set = []
for clause in formula.clauses:
for literal in clause.literals:
symbol = literal[:2]
if symbol not in symbols_set:
symbols_set.append(symbol)
return clauses, symbols_set
def find_pure_symbols(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
| Return pure symbols and their values to satisfy clause.
| Pure symbols are symbols in a formula that exist only in one form,
| either complemented or otherwise.
| For example,
| {{A4 , A3 , A5' , A1 , A3'} , {A4} , {A3}} has pure symbols A4, A5' and A1.
This has the following steps:
1. Ignore clauses that have already evaluated to be ``True``.
2. Find symbols that occur only in one form in the rest of the clauses.
3. Assign value ``True`` or ``False`` depending on whether the symbols occurs
in normal or complemented form respectively.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> pure_symbols, values = find_pure_symbols(clauses, symbols, {})
>>> pure_symbols
['A1', 'A2', 'A3', 'A5']
>>> values
{'A1': True, 'A2': False, 'A3': True, 'A5': False}
"""
pure_symbols = []
assignment: dict[str, bool | None] = {}
literals = []
for clause in clauses:
if clause.evaluate(model):
continue
for literal in clause.literals:
literals.append(literal)
for s in symbols:
sym = s + "'"
if (s in literals and sym not in literals) or (
s not in literals and sym in literals
):
pure_symbols.append(s)
for p in pure_symbols:
assignment[p] = None
for s in pure_symbols:
sym = s + "'"
if s in literals:
assignment[s] = True
elif sym in literals:
assignment[s] = False
return pure_symbols, assignment
def find_unit_clauses(
clauses: list[Clause],
model: dict[str, bool | None], # noqa: ARG001
) -> tuple[list[str], dict[str, bool | None]]:
"""
Returns the unit symbols and their values to satisfy clause.
Unit symbols are symbols in a formula that are:
- Either the only symbol in a clause
- Or all other literals in that clause have been assigned ``False``
This has the following steps:
1. Find symbols that are the only occurrences in a clause.
2. Find symbols in a clause where all other literals are assigned ``False``.
3. Assign ``True`` or ``False`` depending on whether the symbols occurs in
normal or complemented form respectively.
>>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"])
>>> clause2 = Clause(["A4"])
>>> clause3 = Clause(["A3"])
>>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3]))
>>> unit_clauses, values = find_unit_clauses(clauses, {})
>>> unit_clauses
['A4', 'A3']
>>> values
{'A4': True, 'A3': True}
"""
unit_symbols = []
for clause in clauses:
if len(clause) == 1:
unit_symbols.append(next(iter(clause.literals.keys())))
else:
f_count, n_count = 0, 0
for literal, value in clause.literals.items():
if value is False:
f_count += 1
elif value is None:
sym = literal
n_count += 1
if f_count == len(clause) - 1 and n_count == 1:
unit_symbols.append(sym)
assignment: dict[str, bool | None] = {}
for i in unit_symbols:
symbol = i[:2]
assignment[symbol] = len(i) == 2
unit_symbols = [i[:2] for i in unit_symbols]
return unit_symbols, assignment
def dpll_algorithm(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[bool | None, dict[str, bool | None] | None]:
"""
Returns the model if the formula is satisfiable, else ``None``
This has the following steps:
1. If every clause in clauses is ``True``, return ``True``.
2. If some clause in clauses is ``False``, return ``False``.
3. Find pure symbols.
4. Find unit symbols.
>>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])])
>>> clauses, symbols = generate_parameters(formula)
>>> soln, model = dpll_algorithm(clauses, symbols, {})
>>> soln
True
>>> model
{'A4': True}
"""
check_clause_all_true = True
for clause in clauses:
clause_check = clause.evaluate(model)
if clause_check is False:
return False, None
elif clause_check is None:
check_clause_all_true = False
continue
if check_clause_all_true:
return True, model
try:
pure_symbols, assignment = find_pure_symbols(clauses, symbols, model)
except RecursionError:
print("raises a RecursionError and is")
return None, {}
p = None
if len(pure_symbols) > 0:
p, value = pure_symbols[0], assignment[pure_symbols[0]]
if p:
tmp_model = model
tmp_model[p] = value
tmp_symbols = list(symbols)
if p in tmp_symbols:
tmp_symbols.remove(p)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
unit_symbols, assignment = find_unit_clauses(clauses, model)
p = None
if len(unit_symbols) > 0:
p, value = unit_symbols[0], assignment[unit_symbols[0]]
if p:
tmp_model = model
tmp_model[p] = value
tmp_symbols = list(symbols)
if p in tmp_symbols:
tmp_symbols.remove(p)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
p = symbols[0]
rest = symbols[1:]
tmp1, tmp2 = model, model
tmp1[p], tmp2[p] = True, False
return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2)
if __name__ == "__main__":
import doctest
doctest.testmod()
formula = generate_formula()
print(f"The formula {formula} is", end=" ")
clauses, symbols = generate_parameters(formula)
solution, model = dpll_algorithm(clauses, symbols, {})
if solution:
print(f"satisfiable with the assignment {model}.")
else:
print("not satisfiable.")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/linear_congruential_generator.py | other/linear_congruential_generator.py | __author__ = "Tobias Carryer"
from time import time
class LinearCongruentialGenerator:
"""
A pseudorandom number generator.
"""
# The default value for **seed** is the result of a function call, which is not
# normally recommended and causes ruff to raise a B008 error. However, in this case,
# it is acceptable because `LinearCongruentialGenerator.__init__()` will only be
# called once per instance and it ensures that each instance will generate a unique
# sequence of numbers.
def __init__(self, multiplier, increment, modulo, seed=int(time())): # noqa: B008
"""
These parameters are saved and used when nextNumber() is called.
modulo is the largest number that can be generated (exclusive). The most
efficient values are powers of 2. 2^32 is a common value.
"""
self.multiplier = multiplier
self.increment = increment
self.modulo = modulo
self.seed = seed
def next_number(self):
"""
The smallest number that can be generated is zero.
The largest number that can be generated is modulo-1. modulo is set in the
constructor.
"""
self.seed = (self.multiplier * self.seed + self.increment) % self.modulo
return self.seed
if __name__ == "__main__":
# Show the LCG in action.
lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31)
while True:
print(lcg.next_number())
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/password.py | other/password.py | import secrets
from random import shuffle
from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation
def password_generator(length: int = 8) -> str:
"""
Password Generator allows you to generate a random password of length N.
>>> len(password_generator())
8
>>> len(password_generator(length=16))
16
>>> len(password_generator(257))
257
>>> len(password_generator(length=0))
0
>>> len(password_generator(-1))
0
"""
chars = ascii_letters + digits + punctuation
return "".join(secrets.choice(chars) for _ in range(length))
# ALTERNATIVE METHODS
# chars_incl= characters that must be in password
# i= how many letters or characters the password length will be
def alternative_password_generator(chars_incl: str, i: int) -> str:
# Password Generator = full boot with random_number, random_letters, and
# random_character FUNCTIONS
# Put your code here...
i -= len(chars_incl)
quotient = i // 3
remainder = i % 3
# chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) +
# random_number(digits, i / 3) + random_characters(punctuation, i / 3)
chars = (
chars_incl
+ random(ascii_letters, quotient + remainder)
+ random(digits, quotient)
+ random(punctuation, quotient)
)
list_of_chars = list(chars)
shuffle(list_of_chars)
return "".join(list_of_chars)
# random is a generalised function for letters, characters and numbers
def random(chars_incl: str, i: int) -> str:
return "".join(secrets.choice(chars_incl) for _ in range(i))
def is_strong_password(password: str, min_length: int = 8) -> bool:
"""
This will check whether a given password is strong or not. The password must be at
least as long as the provided minimum length, and it must contain at least 1
lowercase letter, 1 uppercase letter, 1 number and 1 special character.
>>> is_strong_password('Hwea7$2!')
True
>>> is_strong_password('Sh0r1')
False
>>> is_strong_password('Hello123')
False
>>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1')
True
>>> is_strong_password('0')
False
"""
if len(password) < min_length:
return False
upper = any(char in ascii_uppercase for char in password)
lower = any(char in ascii_lowercase for char in password)
num = any(char in digits for char in password)
spec_char = any(char in punctuation for char in password)
return upper and lower and num and spec_char
def main():
length = int(input("Please indicate the max length of your password: ").strip())
chars_incl = input(
"Please indicate the characters that must be in your password: "
).strip()
print("Password generated:", password_generator(length))
print(
"Alternative Password generated:",
alternative_password_generator(chars_incl, length),
)
print("[If you are thinking of using this password, You better save it.]")
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/bankers_algorithm.py | other/bankers_algorithm.py | # A Python implementation of the Banker's Algorithm in Operating Systems using
# Processes and Resources
# {
# "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com",
# "Date": 28-10-2018
# }
"""
The Banker's algorithm is a resource allocation and deadlock avoidance algorithm
developed by Edsger Dijkstra that tests for safety by simulating the allocation of
predetermined maximum possible amounts of all resources, and then makes a "s-state"
check to test for possible deadlock conditions for all other pending activities,
before deciding whether allocation should be allowed to continue.
| [Source] Wikipedia
| [Credit] Rosetta Code C implementation helped very much.
| (https://rosettacode.org/wiki/Banker%27s_algorithm)
"""
from __future__ import annotations
import numpy as np
test_claim_vector = [8, 5, 9, 7]
test_allocated_res_table = [
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
test_maximum_claim_table = [
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class BankersAlgorithm:
def __init__(
self,
claim_vector: list[int],
allocated_resources_table: list[list[int]],
maximum_claim_table: list[list[int]],
) -> None:
"""
:param claim_vector: A nxn/nxm list depicting the amount of each resources
(eg. memory, interface, semaphores, etc.) available.
:param allocated_resources_table: A nxn/nxm list depicting the amount of each
resource each process is currently holding
:param maximum_claim_table: A nxn/nxm list depicting how much of each resource
the system currently has available
"""
self.__claim_vector = claim_vector
self.__allocated_resources_table = allocated_resources_table
self.__maximum_claim_table = maximum_claim_table
def __processes_resource_summation(self) -> list[int]:
"""
Check for allocated resources in line with each resource in the claim vector
"""
return [
sum(p_item[i] for p_item in self.__allocated_resources_table)
for i in range(len(self.__allocated_resources_table[0]))
]
def __available_resources(self) -> list[int]:
"""
Check for available resources in line with each resource in the claim vector
"""
return np.array(self.__claim_vector) - np.array(
self.__processes_resource_summation()
)
def __need(self) -> list[list[int]]:
"""
Implement safety checker that calculates the needs by ensuring that
``max_claim[i][j] - alloc_table[i][j] <= avail[j]``
"""
return [
list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource))
for i, allocated_resource in enumerate(self.__allocated_resources_table)
]
def __need_index_manager(self) -> dict[int, list[int]]:
"""
This function builds an index control dictionary to track original ids/indices
of processes when altered during execution of method "main"
:Return: {0: [a: int, b: int], 1: [c: int, d: int]}
>>> index_control = BankersAlgorithm(
... test_claim_vector, test_allocated_res_table, test_maximum_claim_table
... )._BankersAlgorithm__need_index_manager()
>>> {key: [int(x) for x in value] for key, value
... in index_control.items()} # doctest: +NORMALIZE_WHITESPACE
{0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0],
4: [2, 0, 0, 3]}
"""
return {self.__need().index(i): i for i in self.__need()}
def main(self, **kwargs) -> None:
"""
Utilize various methods in this class to simulate the Banker's algorithm
:Return: None
>>> BankersAlgorithm(test_claim_vector, test_allocated_res_table,
... test_maximum_claim_table).main(describe=True)
Allocated Resource Table
P1 2 0 1 1
<BLANKLINE>
P2 0 1 2 1
<BLANKLINE>
P3 4 0 0 3
<BLANKLINE>
P4 0 2 1 0
<BLANKLINE>
P5 1 0 3 0
<BLANKLINE>
System Resource Table
P1 3 2 1 4
<BLANKLINE>
P2 0 2 5 2
<BLANKLINE>
P3 5 1 0 5
<BLANKLINE>
P4 1 5 3 0
<BLANKLINE>
P5 3 0 3 3
<BLANKLINE>
Current Usage by Active Processes: 8 5 9 7
Initial Available Resources: 1 2 2 2
__________________________________________________
<BLANKLINE>
Process 3 is executing.
Updated available resource stack for processes: 5 2 2 5
The process is in a safe state.
<BLANKLINE>
Process 1 is executing.
Updated available resource stack for processes: 7 2 3 6
The process is in a safe state.
<BLANKLINE>
Process 2 is executing.
Updated available resource stack for processes: 7 3 5 7
The process is in a safe state.
<BLANKLINE>
Process 4 is executing.
Updated available resource stack for processes: 7 5 6 7
The process is in a safe state.
<BLANKLINE>
Process 5 is executing.
Updated available resource stack for processes: 8 5 9 7
The process is in a safe state.
<BLANKLINE>
"""
need_list = self.__need()
alloc_resources_table = self.__allocated_resources_table
available_resources = self.__available_resources()
need_index_manager = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print("_" * 50 + "\n")
while need_list:
safe = False
for each_need in need_list:
execution = True
for index, need in enumerate(each_need):
if need > available_resources[index]:
execution = False
break
if execution:
safe = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
process_number = original_need_index
print(f"Process {process_number + 1} is executing.")
# remove the process run from stack
need_list.remove(each_need)
# update available/freed resources stack
available_resources = np.array(available_resources) + np.array(
alloc_resources_table[process_number]
)
print(
"Updated available resource stack for processes: "
+ " ".join([str(x) for x in available_resources])
)
break
if safe:
print("The process is in a safe state.\n")
else:
print("System in unsafe state. Aborting...\n")
break
def __pretty_data(self):
"""
Properly align display of the algorithm's solution
"""
print(" " * 9 + "Allocated Resource Table")
for item in self.__allocated_resources_table:
print(
f"P{self.__allocated_resources_table.index(item) + 1}"
+ " ".join(f"{it:>8}" for it in item)
+ "\n"
)
print(" " * 9 + "System Resource Table")
for item in self.__maximum_claim_table:
print(
f"P{self.__maximum_claim_table.index(item) + 1}"
+ " ".join(f"{it:>8}" for it in item)
+ "\n"
)
print(
"Current Usage by Active Processes: "
+ " ".join(str(x) for x in self.__claim_vector)
)
print(
"Initial Available Resources: "
+ " ".join(str(x) for x in self.__available_resources())
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/lfu_cache.py | other/lfu_cache.py | from __future__ import annotations
from collections.abc import Callable
from typing import TypeVar
T = TypeVar("T")
U = TypeVar("U")
class DoubleLinkedListNode[T, U]:
"""
Double Linked List Node built specifically for LFU Cache
>>> node = DoubleLinkedListNode(1,1)
>>> node
Node: key: 1, val: 1, freq: 0, has next: False, has prev: False
"""
def __init__(self, key: T | None, val: U | None):
self.key = key
self.val = val
self.freq: int = 0
self.next: DoubleLinkedListNode[T, U] | None = None
self.prev: DoubleLinkedListNode[T, U] | None = None
def __repr__(self) -> str:
return (
f"Node: key: {self.key}, val: {self.val}, freq: {self.freq}, "
f"has next: {self.next is not None}, has prev: {self.prev is not None}"
)
class DoubleLinkedList[T, U]:
"""
Double Linked List built specifically for LFU Cache
>>> dll: DoubleLinkedList = DoubleLinkedList()
>>> dll
DoubleLinkedList,
Node: key: None, val: None, freq: 0, has next: True, has prev: False,
Node: key: None, val: None, freq: 0, has next: False, has prev: True
>>> first_node = DoubleLinkedListNode(1,10)
>>> first_node
Node: key: 1, val: 10, freq: 0, has next: False, has prev: False
>>> dll.add(first_node)
>>> dll
DoubleLinkedList,
Node: key: None, val: None, freq: 0, has next: True, has prev: False,
Node: key: 1, val: 10, freq: 1, has next: True, has prev: True,
Node: key: None, val: None, freq: 0, has next: False, has prev: True
>>> # node is mutated
>>> first_node
Node: key: 1, val: 10, freq: 1, has next: True, has prev: True
>>> second_node = DoubleLinkedListNode(2,20)
>>> second_node
Node: key: 2, val: 20, freq: 0, has next: False, has prev: False
>>> dll.add(second_node)
>>> dll
DoubleLinkedList,
Node: key: None, val: None, freq: 0, has next: True, has prev: False,
Node: key: 1, val: 10, freq: 1, has next: True, has prev: True,
Node: key: 2, val: 20, freq: 1, has next: True, has prev: True,
Node: key: None, val: None, freq: 0, has next: False, has prev: True
>>> removed_node = dll.remove(first_node)
>>> assert removed_node == first_node
>>> dll
DoubleLinkedList,
Node: key: None, val: None, freq: 0, has next: True, has prev: False,
Node: key: 2, val: 20, freq: 1, has next: True, has prev: True,
Node: key: None, val: None, freq: 0, has next: False, has prev: True
>>> # Attempt to remove node not on list
>>> removed_node = dll.remove(first_node)
>>> removed_node is None
True
>>> # Attempt to remove head or rear
>>> dll.head
Node: key: None, val: None, freq: 0, has next: True, has prev: False
>>> dll.remove(dll.head) is None
True
>>> # Attempt to remove head or rear
>>> dll.rear
Node: key: None, val: None, freq: 0, has next: False, has prev: True
>>> dll.remove(dll.rear) is None
True
"""
def __init__(self) -> None:
self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None)
self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None)
self.head.next, self.rear.prev = self.rear, self.head
def __repr__(self) -> str:
rep = ["DoubleLinkedList"]
node = self.head
while node.next is not None:
rep.append(str(node))
node = node.next
rep.append(str(self.rear))
return ",\n ".join(rep)
def add(self, node: DoubleLinkedListNode[T, U]) -> None:
"""
Adds the given node at the tail of the list and shifting it to proper position
"""
previous = self.rear.prev
# All nodes other than self.head are guaranteed to have non-None previous
assert previous is not None
previous.next = node
node.prev = previous
self.rear.prev = node
node.next = self.rear
node.freq += 1
self._position_node(node)
def _position_node(self, node: DoubleLinkedListNode[T, U]) -> None:
"""
Moves node forward to maintain invariant of sort by freq value
"""
while node.prev is not None and node.prev.freq > node.freq:
# swap node with previous node
previous_node = node.prev
node.prev = previous_node.prev
previous_node.next = node.prev
node.next = previous_node
previous_node.prev = node
def remove(
self, node: DoubleLinkedListNode[T, U]
) -> DoubleLinkedListNode[T, U] | None:
"""
Removes and returns the given node from the list
Returns None if node.prev or node.next is None
"""
if node.prev is None or node.next is None:
return None
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
return node
class LFUCache[T, U]:
"""
LFU Cache to store a given capacity of data. Can be used as a stand-alone object
or as a function decorator.
>>> cache = LFUCache(2)
>>> cache.put(1, 1)
>>> cache.put(2, 2)
>>> cache.get(1)
1
>>> cache.put(3, 3)
>>> cache.get(2) is None
True
>>> cache.put(4, 4)
>>> cache.get(1) is None
True
>>> cache.get(3)
3
>>> cache.get(4)
4
>>> cache
CacheInfo(hits=3, misses=2, capacity=2, current_size=2)
>>> @LFUCache.decorator(100)
... def fib(num):
... if num in (1, 2):
... return 1
... return fib(num - 1) + fib(num - 2)
>>> for i in range(1, 101):
... res = fib(i)
>>> fib.cache_info()
CacheInfo(hits=196, misses=100, capacity=100, current_size=100)
"""
def __init__(self, capacity: int):
self.list: DoubleLinkedList[T, U] = DoubleLinkedList()
self.capacity = capacity
self.num_keys = 0
self.hits = 0
self.miss = 0
self.cache: dict[T, DoubleLinkedListNode[T, U]] = {}
def __repr__(self) -> str:
"""
Return the details for the cache instance
[hits, misses, capacity, current_size]
"""
return (
f"CacheInfo(hits={self.hits}, misses={self.miss}, "
f"capacity={self.capacity}, current_size={self.num_keys})"
)
def __contains__(self, key: T) -> bool:
"""
>>> cache = LFUCache(1)
>>> 1 in cache
False
>>> cache.put(1, 1)
>>> 1 in cache
True
"""
return key in self.cache
def get(self, key: T) -> U | None:
"""
Returns the value for the input key and updates the Double Linked List. Returns
Returns None if key is not present in cache
"""
if key in self.cache:
self.hits += 1
value_node: DoubleLinkedListNode[T, U] = self.cache[key]
node = self.list.remove(self.cache[key])
assert node == value_node
# node is guaranteed not None because it is in self.cache
assert node is not None
self.list.add(node)
return node.val
self.miss += 1
return None
def put(self, key: T, value: U) -> None:
"""
Sets the value for the input key and updates the Double Linked List
"""
if key not in self.cache:
if self.num_keys >= self.capacity:
# delete first node when over capacity
first_node = self.list.head.next
# guaranteed to have a non-None first node when num_keys > 0
# explain to type checker via assertions
assert first_node is not None
assert first_node.key is not None
assert self.list.remove(first_node) is not None
# first_node guaranteed to be in list
del self.cache[first_node.key]
self.num_keys -= 1
self.cache[key] = DoubleLinkedListNode(key, value)
self.list.add(self.cache[key])
self.num_keys += 1
else:
node = self.list.remove(self.cache[key])
assert node is not None # node guaranteed to be in list
node.val = value
self.list.add(node)
@classmethod
def decorator(
cls: type[LFUCache[T, U]], size: int = 128
) -> Callable[[Callable[[T], U]], Callable[..., U]]:
"""
Decorator version of LFU Cache
Decorated function must be function of T -> U
"""
def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]:
# variable to map the decorator functions to their respective instance
decorator_function_to_instance_map: dict[
Callable[[T], U], LFUCache[T, U]
] = {}
def cache_decorator_wrapper(*args: T) -> U:
if func not in decorator_function_to_instance_map:
decorator_function_to_instance_map[func] = LFUCache(size)
result = decorator_function_to_instance_map[func].get(args[0])
if result is None:
result = func(*args)
decorator_function_to_instance_map[func].put(args[0], result)
return result
def cache_info() -> LFUCache[T, U]:
return decorator_function_to_instance_map[func]
setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
return cache_decorator_wrapper
return cache_decorator_inner
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/maximum_subsequence.py | other/maximum_subsequence.py | from collections.abc import Sequence
def max_subsequence_sum(nums: Sequence[int] | None = None) -> int:
"""Return the maximum possible sum amongst all non - empty subsequences.
Raises:
ValueError: when nums is empty.
>>> max_subsequence_sum([1,2,3,4,-2])
10
>>> max_subsequence_sum([-2, -3, -1, -4, -6])
-1
>>> max_subsequence_sum([])
Traceback (most recent call last):
. . .
ValueError: Input sequence should not be empty
>>> max_subsequence_sum()
Traceback (most recent call last):
. . .
ValueError: Input sequence should not be empty
"""
if nums is None or not nums:
raise ValueError("Input sequence should not be empty")
ans = nums[0]
for i in range(1, len(nums)):
num = nums[i]
ans = max(ans, ans + num, num)
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
n = int(input("Enter number of elements : ").strip())
array = list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
print(max_subsequence_sum(array))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/guess_the_number_search.py | other/guess_the_number_search.py | """
guess the number using lower,higher and the value to find or guess
solution works by dividing lower and higher of number guessed
suppose lower is 0, higher is 1000 and the number to guess is 355
>>> guess_the_number(10, 1000, 17)
started...
guess the number : 17
details : [505, 257, 133, 71, 40, 25, 17]
"""
def temp_input_value(
min_val: int = 10, max_val: int = 1000, option: bool = True
) -> int:
"""
Temporary input values for tests
>>> temp_input_value(option=True)
10
>>> temp_input_value(option=False)
1000
>>> temp_input_value(min_val=100, option=True)
100
>>> temp_input_value(min_val=100, max_val=50)
Traceback (most recent call last):
...
ValueError: Invalid value for min_val or max_val (min_value < max_value)
>>> temp_input_value("ten","fifty",1)
Traceback (most recent call last):
...
AssertionError: Invalid type of value(s) specified to function!
>>> temp_input_value(min_val=-100, max_val=500)
-100
>>> temp_input_value(min_val=-5100, max_val=-100)
-5100
"""
assert (
isinstance(min_val, int)
and isinstance(max_val, int)
and isinstance(option, bool)
), "Invalid type of value(s) specified to function!"
if min_val > max_val:
raise ValueError("Invalid value for min_val or max_val (min_value < max_value)")
return min_val if option else max_val
def get_avg(number_1: int, number_2: int) -> int:
"""
Return the mid-number(whole) of two integers a and b
>>> get_avg(10, 15)
12
>>> get_avg(20, 300)
160
>>> get_avg("abcd", 300)
Traceback (most recent call last):
...
TypeError: can only concatenate str (not "int") to str
>>> get_avg(10.5,50.25)
30
"""
return int((number_1 + number_2) / 2)
def guess_the_number(lower: int, higher: int, to_guess: int) -> None:
"""
The `guess_the_number` function that guess the number by some operations
and using inner functions
>>> guess_the_number(10, 1000, 17)
started...
guess the number : 17
details : [505, 257, 133, 71, 40, 25, 17]
>>> guess_the_number(-10000, 10000, 7)
started...
guess the number : 7
details : [0, 5000, 2500, 1250, 625, 312, 156, 78, 39, 19, 9, 4, 6, 7]
>>> guess_the_number(10, 1000, "a")
Traceback (most recent call last):
...
AssertionError: argument values must be type of "int"
>>> guess_the_number(10, 1000, 5)
Traceback (most recent call last):
...
ValueError: guess value must be within the range of lower and higher value
>>> guess_the_number(10000, 100, 5)
Traceback (most recent call last):
...
ValueError: argument value for lower and higher must be(lower > higher)
"""
assert (
isinstance(lower, int) and isinstance(higher, int) and isinstance(to_guess, int)
), 'argument values must be type of "int"'
if lower > higher:
raise ValueError("argument value for lower and higher must be(lower > higher)")
if not lower < to_guess < higher:
raise ValueError(
"guess value must be within the range of lower and higher value"
)
def answer(number: int) -> str:
"""
Returns value by comparing with entered `to_guess` number
"""
if number > to_guess:
return "high"
elif number < to_guess:
return "low"
else:
return "same"
print("started...")
last_lowest = lower
last_highest = higher
last_numbers = []
while True:
number = get_avg(last_lowest, last_highest)
last_numbers.append(number)
if answer(number) == "low":
last_lowest = number
elif answer(number) == "high":
last_highest = number
else:
break
print(f"guess the number : {last_numbers[-1]}")
print(f"details : {last_numbers!s}")
def main() -> None:
"""
starting point or function of script
"""
lower = int(input("Enter lower value : ").strip())
higher = int(input("Enter high value : ").strip())
guess = int(input("Enter value to guess : ").strip())
guess_the_number(lower, higher, guess)
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/magicdiamondpattern.py | other/magicdiamondpattern.py | # Python program for generating diamond pattern in Python 3.7+
# Function to print upper half of diamond (pyramid)
def floyd(n):
"""
Print the upper half of a diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> floyd(3)
' * \\n * * \\n* * * \\n'
>>> floyd(5)
' * \\n * * \\n * * * \\n * * * * \\n* * * * * \\n'
"""
result = ""
for i in range(n):
for _ in range(n - i - 1): # printing spaces
result += " "
for _ in range(i + 1): # printing stars
result += "* "
result += "\n"
return result
# Function to print lower half of diamond (pyramid)
def reverse_floyd(n):
"""
Print the lower half of a diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> reverse_floyd(3)
'* * * \\n * * \\n * \\n '
>>> reverse_floyd(5)
'* * * * * \\n * * * * \\n * * * \\n * * \\n * \\n '
"""
result = ""
for i in range(n, 0, -1):
for _ in range(i, 0, -1): # printing stars
result += "* "
result += "\n"
for _ in range(n - i + 1, 0, -1): # printing spaces
result += " "
return result
# Function to print complete diamond pattern of "*"
def pretty_print(n):
"""
Print a complete diamond pattern with '*' characters.
Args:
n (int): Size of the pattern.
Examples:
>>> pretty_print(0)
' ... .... nothing printing :('
>>> pretty_print(3)
' * \\n * * \\n* * * \\n* * * \\n * * \\n * \\n '
"""
if n <= 0:
return " ... .... nothing printing :("
upper_half = floyd(n) # upper half
lower_half = reverse_floyd(n) # lower half
return upper_half + lower_half
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/alternative_list_arrange.py | other/alternative_list_arrange.py | def alternative_list_arrange(first_input_list: list, second_input_list: list) -> list:
"""
The method arranges two lists as one list in alternative forms of the list elements.
:param first_input_list:
:param second_input_list:
:return: List
>>> alternative_list_arrange([1, 2, 3, 4, 5], ["A", "B", "C"])
[1, 'A', 2, 'B', 3, 'C', 4, 5]
>>> alternative_list_arrange(["A", "B", "C"], [1, 2, 3, 4, 5])
['A', 1, 'B', 2, 'C', 3, 4, 5]
>>> alternative_list_arrange(["X", "Y", "Z"], [9, 8, 7, 6])
['X', 9, 'Y', 8, 'Z', 7, 6]
>>> alternative_list_arrange([1, 2, 3, 4, 5], [])
[1, 2, 3, 4, 5]
"""
first_input_list_length: int = len(first_input_list)
second_input_list_length: int = len(second_input_list)
abs_length: int = (
first_input_list_length
if first_input_list_length > second_input_list_length
else second_input_list_length
)
output_result_list: list = []
for char_count in range(abs_length):
if char_count < first_input_list_length:
output_result_list.append(first_input_list[char_count])
if char_count < second_input_list_length:
output_result_list.append(second_input_list[char_count])
return output_result_list
if __name__ == "__main__":
print(alternative_list_arrange(["A", "B", "C"], [1, 2, 3, 4, 5]), end=" ")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/gauss_easter.py | other/gauss_easter.py | """
https://en.wikipedia.org/wiki/Computus#Gauss'_Easter_algorithm
"""
import math
from datetime import UTC, datetime, timedelta
def gauss_easter(year: int) -> datetime:
"""
Calculation Gregorian easter date for given year
>>> gauss_easter(2007)
datetime.datetime(2007, 4, 8, 0, 0, tzinfo=datetime.timezone.utc)
>>> gauss_easter(2008)
datetime.datetime(2008, 3, 23, 0, 0, tzinfo=datetime.timezone.utc)
>>> gauss_easter(2020)
datetime.datetime(2020, 4, 12, 0, 0, tzinfo=datetime.timezone.utc)
>>> gauss_easter(2021)
datetime.datetime(2021, 4, 4, 0, 0, tzinfo=datetime.timezone.utc)
"""
metonic_cycle = year % 19
julian_leap_year = year % 4
non_leap_year = year % 7
leap_day_inhibits = math.floor(year / 100)
lunar_orbit_correction = math.floor((13 + 8 * leap_day_inhibits) / 25)
leap_day_reinstall_number = leap_day_inhibits / 4
secular_moon_shift = (
15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number
) % 30
century_starting_point = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7
# days to be added to March 21
days_to_add = (19 * metonic_cycle + secular_moon_shift) % 30
# PHM -> Paschal Full Moon
days_from_phm_to_sunday = (
2 * julian_leap_year
+ 4 * non_leap_year
+ 6 * days_to_add
+ century_starting_point
) % 7
if days_to_add == 29 and days_from_phm_to_sunday == 6:
return datetime(year, 4, 19, tzinfo=UTC)
elif days_to_add == 28 and days_from_phm_to_sunday == 6:
return datetime(year, 4, 18, tzinfo=UTC)
else:
return datetime(year, 3, 22, tzinfo=UTC) + timedelta(
days=int(days_to_add + days_from_phm_to_sunday)
)
if __name__ == "__main__":
for year in (1994, 2000, 2010, 2021, 2023, 2032, 2100):
tense = "will be" if year > datetime.now(tz=UTC).year else "was"
print(f"Easter in {year} {tense} {gauss_easter(year)}")
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/h_index.py | other/h_index.py | """
Task:
Given an array of integers citations where citations[i] is the number of
citations a researcher received for their ith paper, return compute the
researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an
index h if h of their n papers have at least h citations each, and the other
n - h papers have no more than h citations each.
If there are several possible values for h, the maximum one is taken as the
h-index.
H-Index link: https://en.wikipedia.org/wiki/H-index
Implementation notes:
Use sorting of array
Leetcode link: https://leetcode.com/problems/h-index/description/
n = len(citations)
Runtime Complexity: O(n * log(n))
Space Complexity: O(1)
"""
def h_index(citations: list[int]) -> int:
"""
Return H-index of citations
>>> h_index([3, 0, 6, 1, 5])
3
>>> h_index([1, 3, 1])
1
>>> h_index([1, 2, 3])
2
>>> h_index('test')
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
>>> h_index([1,2,'3'])
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
>>> h_index([1,2,-3])
Traceback (most recent call last):
...
ValueError: The citations should be a list of non negative integers.
"""
# validate:
if not isinstance(citations, list) or not all(
isinstance(item, int) and item >= 0 for item in citations
):
raise ValueError("The citations should be a list of non negative integers.")
citations.sort()
len_citations = len(citations)
for i in range(len_citations):
if citations[len_citations - 1 - i] <= i:
return i
return len_citations
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/word_search.py | other/word_search.py | """
Creates a random wordsearch with eight different directions
that are best described as compass locations.
@ https://en.wikipedia.org/wiki/Word_search
"""
from random import choice, randint, shuffle
# The words to display on the word search -
# can be made dynamic by randonly selecting a certain number of
# words from a predefined word file, while ensuring the character
# count fits within the matrix size (n x m)
WORDS = ["cat", "dog", "snake", "fish"]
WIDTH = 10
HEIGHT = 10
class WordSearch:
"""
>>> ws = WordSearch(WORDS, WIDTH, HEIGHT)
>>> ws.board # doctest: +ELLIPSIS
[[None, ..., None], ..., [None, ..., None]]
>>> ws.generate_board()
"""
def __init__(self, words: list[str], width: int, height: int) -> None:
self.words = words
self.width = width
self.height = height
# Board matrix holding each letter
self.board: list[list[str | None]] = [[None] * width for _ in range(height)]
def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_north("cat", [2], [2])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, 't'],
[None, None, 'a'],
[None, None, 'c']]
>>> ws.insert_north("at", [0, 1, 2], [2, 1])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, 't', 't'],
[None, 'a', 'a'],
[None, None, 'c']]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space above the row to fit in the word
if word_length > row + 1:
continue
# Attempt to insert the word into each column
for col in cols:
# Only check to be made here is if there are existing letters
# above the column that will be overwritten
letters_above = [self.board[row - i][col] for i in range(word_length)]
if all(letter is None for letter in letters_above):
# Successful, insert the word north
for i in range(word_length):
self.board[row - i][col] = word[i]
return
def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_northeast("cat", [2], [0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, 't'],
[None, 'a', None],
['c', None, None]]
>>> ws.insert_northeast("at", [0, 1], [2, 1, 0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, 't', 't'],
['a', 'a', None],
['c', None, None]]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space for the word above the row
if word_length > row + 1:
continue
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the right of the word as well as above
if word_length + col > self.width:
continue
# Check if there are existing letters
# to the right of the column that will be overwritten
letters_diagonal_left = [
self.board[row - i][col + i] for i in range(word_length)
]
if all(letter is None for letter in letters_diagonal_left):
# Successful, insert the word northeast
for i in range(word_length):
self.board[row - i][col + i] = word[i]
return
def insert_east(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_east("cat", [1], [0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, None],
['c', 'a', 't'],
[None, None, None]]
>>> ws.insert_east("at", [1, 0], [2, 1, 0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, 'a', 't'],
['c', 'a', 't'],
[None, None, None]]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the right of the word
if word_length + col > self.width:
continue
# Check if there are existing letters
# to the right of the column that will be overwritten
letters_left = [self.board[row][col + i] for i in range(word_length)]
if all(letter is None for letter in letters_left):
# Successful, insert the word east
for i in range(word_length):
self.board[row][col + i] = word[i]
return
def insert_southeast(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_southeast("cat", [0], [0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['c', None, None],
[None, 'a', None],
[None, None, 't']]
>>> ws.insert_southeast("at", [1, 0], [2, 1, 0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['c', None, None],
['a', 'a', None],
[None, 't', 't']]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space for the word below the row
if word_length + row > self.height:
continue
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the right of the word as well as below
if word_length + col > self.width:
continue
# Check if there are existing letters
# to the right of the column that will be overwritten
letters_diagonal_left = [
self.board[row + i][col + i] for i in range(word_length)
]
if all(letter is None for letter in letters_diagonal_left):
# Successful, insert the word southeast
for i in range(word_length):
self.board[row + i][col + i] = word[i]
return
def insert_south(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_south("cat", [0], [0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['c', None, None],
['a', None, None],
['t', None, None]]
>>> ws.insert_south("at", [2, 1, 0], [0, 1, 2])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['c', None, None],
['a', 'a', None],
['t', 't', None]]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space below the row to fit in the word
if word_length + row > self.height:
continue
# Attempt to insert the word into each column
for col in cols:
# Only check to be made here is if there are existing letters
# below the column that will be overwritten
letters_below = [self.board[row + i][col] for i in range(word_length)]
if all(letter is None for letter in letters_below):
# Successful, insert the word south
for i in range(word_length):
self.board[row + i][col] = word[i]
return
def insert_southwest(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_southwest("cat", [0], [2])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, 'c'],
[None, 'a', None],
['t', None, None]]
>>> ws.insert_southwest("at", [1, 2], [2, 1, 0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, 'c'],
[None, 'a', 'a'],
['t', 't', None]]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space for the word below the row
if word_length + row > self.height:
continue
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the left of the word as well as below
if word_length > col + 1:
continue
# Check if there are existing letters
# to the right of the column that will be overwritten
letters_diagonal_left = [
self.board[row + i][col - i] for i in range(word_length)
]
if all(letter is None for letter in letters_diagonal_left):
# Successful, insert the word southwest
for i in range(word_length):
self.board[row + i][col - i] = word[i]
return
def insert_west(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_west("cat", [1], [2])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[[None, None, None],
['t', 'a', 'c'],
[None, None, None]]
>>> ws.insert_west("at", [1, 0], [1, 2, 0])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['t', 'a', None],
['t', 'a', 'c'],
[None, None, None]]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the left of the word
if word_length > col + 1:
continue
# Check if there are existing letters
# to the left of the column that will be overwritten
letters_left = [self.board[row][col - i] for i in range(word_length)]
if all(letter is None for letter in letters_left):
# Successful, insert the word west
for i in range(word_length):
self.board[row][col - i] = word[i]
return
def insert_northwest(self, word: str, rows: list[int], cols: list[int]) -> None:
"""
>>> ws = WordSearch(WORDS, 3, 3)
>>> ws.insert_northwest("cat", [2], [2])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['t', None, None],
[None, 'a', None],
[None, None, 'c']]
>>> ws.insert_northwest("at", [1, 2], [0, 1])
>>> ws.board # doctest: +NORMALIZE_WHITESPACE
[['t', None, None],
['t', 'a', None],
[None, 'a', 'c']]
"""
word_length = len(word)
# Attempt to insert the word into each row and when successful, exit
for row in rows:
# Check if there is space for the word above the row
if word_length > row + 1:
continue
# Attempt to insert the word into each column
for col in cols:
# Check if there is space to the left of the word as well as above
if word_length > col + 1:
continue
# Check if there are existing letters
# to the right of the column that will be overwritten
letters_diagonal_left = [
self.board[row - i][col - i] for i in range(word_length)
]
if all(letter is None for letter in letters_diagonal_left):
# Successful, insert the word northwest
for i in range(word_length):
self.board[row - i][col - i] = word[i]
return
def generate_board(self) -> None:
"""
Generates a board with a random direction for each word.
>>> wt = WordSearch(WORDS, WIDTH, HEIGHT)
>>> wt.generate_board()
>>> len(list(filter(lambda word: word is not None, sum(wt.board, start=[])))
... ) == sum(map(lambda word: len(word), WORDS))
True
"""
directions = (
self.insert_north,
self.insert_northeast,
self.insert_east,
self.insert_southeast,
self.insert_south,
self.insert_southwest,
self.insert_west,
self.insert_northwest,
)
for word in self.words:
# Shuffle the row order and column order that is used when brute forcing
# the insertion of the word
rows, cols = list(range(self.height)), list(range(self.width))
shuffle(rows)
shuffle(cols)
# Insert the word via the direction
choice(directions)(word, rows, cols)
def visualise_word_search(
board: list[list[str | None]] | None = None, *, add_fake_chars: bool = True
) -> None:
"""
Graphically displays the word search in the terminal.
>>> ws = WordSearch(WORDS, 5, 5)
>>> ws.insert_north("cat", [4], [4])
>>> visualise_word_search(
... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE
# # # # #
# # # # #
# # # # t
# # # # a
# # # # c
>>> ws.insert_northeast("snake", [4], [4, 3, 2, 1, 0])
>>> visualise_word_search(
... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE
# # # # e
# # # k #
# # a # t
# n # # a
s # # # c
"""
if board is None:
word_search = WordSearch(WORDS, WIDTH, HEIGHT)
word_search.generate_board()
board = word_search.board
result = ""
for row in range(len(board)):
for col in range(len(board[0])):
character = "#"
if (letter := board[row][col]) is not None:
character = letter
# Empty char, so add a fake char
elif add_fake_chars:
character = chr(randint(97, 122))
result += f"{character} "
result += "\n"
print(result, end="")
if __name__ == "__main__":
import doctest
doctest.testmod()
visualise_word_search()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/majority_vote_algorithm.py | other/majority_vote_algorithm.py | """
This is Booyer-Moore Majority Vote Algorithm. The problem statement goes like this:
Given an integer array of size n, find all elements that appear more than ⌊ n/k ⌋ times.
We have to solve in O(n) time and O(1) Space.
URL : https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
"""
from collections import Counter
def majority_vote(votes: list[int], votes_needed_to_win: int) -> list[int]:
"""
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 3)
[2]
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 2)
[]
>>> majority_vote([1, 2, 2, 3, 1, 3, 2], 4)
[1, 2, 3]
"""
majority_candidate_counter: Counter[int] = Counter()
for vote in votes:
majority_candidate_counter[vote] += 1
if len(majority_candidate_counter) == votes_needed_to_win:
majority_candidate_counter -= Counter(set(majority_candidate_counter))
majority_candidate_counter = Counter(
vote for vote in votes if vote in majority_candidate_counter
)
return [
vote
for vote in majority_candidate_counter
if majority_candidate_counter[vote] > len(votes) / votes_needed_to_win
]
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/quine.py | other/quine.py | #!/bin/python3
# ruff: noqa: PLC3002
"""
Quine:
A quine is a computer program which takes no input and produces a copy of its
own source code as its only output (disregarding this docstring and the shebang).
More info on: https://en.wikipedia.org/wiki/Quine_(computing)
"""
print((lambda quine: quine % quine)("print((lambda quine: quine %% quine)(%r))"))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/sdes.py | other/sdes.py | def apply_table(inp, table):
"""
>>> apply_table("0123456789", list(range(10)))
'9012345678'
>>> apply_table("0123456789", list(range(9, -1, -1)))
'8765432109'
"""
res = ""
for i in table:
res += inp[i - 1]
return res
def left_shift(data):
"""
>>> left_shift("0123456789")
'1234567890'
"""
return data[1:] + data[0]
def xor(a, b):
"""
>>> xor("01010101", "00001111")
'01011010'
"""
res = ""
for i in range(len(a)):
if a[i] == b[i]:
res += "0"
else:
res += "1"
return res
def apply_sbox(s, data):
row = int("0b" + data[0] + data[-1], 2)
col = int("0b" + data[1:3], 2)
return bin(s[row][col])[2:]
def function(expansion, s0, s1, key, message):
left = message[:4]
right = message[4:]
temp = apply_table(right, expansion)
temp = xor(temp, key)
left_bin_str = apply_sbox(s0, temp[:4])
right_bin_str = apply_sbox(s1, temp[4:])
left_bin_str = "0" * (2 - len(left_bin_str)) + left_bin_str
right_bin_str = "0" * (2 - len(right_bin_str)) + right_bin_str
temp = apply_table(left_bin_str + right_bin_str, p4_table)
temp = xor(left, temp)
return temp + right
if __name__ == "__main__":
key = input("Enter 10 bit key: ")
message = input("Enter 8 bit message: ")
p8_table = [6, 3, 7, 4, 8, 5, 10, 9]
p10_table = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]
p4_table = [2, 4, 3, 1]
IP = [2, 6, 3, 1, 4, 8, 5, 7]
IP_inv = [4, 1, 3, 5, 7, 2, 8, 6]
expansion = [4, 1, 2, 3, 2, 3, 4, 1]
s0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]
s1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
# key generation
temp = apply_table(key, p10_table)
left = temp[:5]
right = temp[5:]
left = left_shift(left)
right = left_shift(right)
key1 = apply_table(left + right, p8_table)
left = left_shift(left)
right = left_shift(right)
left = left_shift(left)
right = left_shift(right)
key2 = apply_table(left + right, p8_table)
# encryption
temp = apply_table(message, IP)
temp = function(expansion, s0, s1, key1, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key2, temp)
CT = apply_table(temp, IP_inv)
print("Cipher text is:", CT)
# decryption
temp = apply_table(CT, IP)
temp = function(expansion, s0, s1, key2, temp)
temp = temp[4:] + temp[:4]
temp = function(expansion, s0, s1, key1, temp)
PT = apply_table(temp, IP_inv)
print("Plain text after decypting is:", PT)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/tower_of_hanoi.py | other/tower_of_hanoi.py | def move_tower(height, from_pole, to_pole, with_pole):
"""
>>> move_tower(3, 'A', 'B', 'C')
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B
"""
if height >= 1:
move_tower(height - 1, from_pole, with_pole, to_pole)
move_disk(from_pole, to_pole)
move_tower(height - 1, with_pole, to_pole, from_pole)
def move_disk(fp, tp):
print("moving disk from", fp, "to", tp)
def main():
height = int(input("Height of hanoi: ").strip())
move_tower(height, "A", "B", "C")
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/scoring_algorithm.py | other/scoring_algorithm.py | """
| developed by: markmelnic
| original repo: https://github.com/markmelnic/Scoring-Algorithm
Analyse data using a range based percentual proximity algorithm
and calculate the linear maximum likelihood estimation.
The basic principle is that all values supplied will be broken
down to a range from ``0`` to ``1`` and each column's score will be added
up to get the total score.
Example for data of vehicles
::
price|mileage|registration_year
20k |60k |2012
22k |50k |2011
23k |90k |2015
16k |210k |2010
We want the vehicle with the lowest price,
lowest mileage but newest registration year.
Thus the weights for each column are as follows:
``[0, 0, 1]``
"""
def get_data(source_data: list[list[float]]) -> list[list[float]]:
"""
>>> get_data([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]])
[[20.0, 23.0, 22.0], [60.0, 90.0, 50.0], [2012.0, 2015.0, 2011.0]]
"""
data_lists: list[list[float]] = []
for data in source_data:
for i, el in enumerate(data):
if len(data_lists) < i + 1:
data_lists.append([])
data_lists[i].append(float(el))
return data_lists
def calculate_each_score(
data_lists: list[list[float]], weights: list[int]
) -> list[list[float]]:
"""
>>> calculate_each_score([[20, 23, 22], [60, 90, 50], [2012, 2015, 2011]],
... [0, 0, 1])
[[1.0, 0.0, 0.33333333333333337], [0.75, 0.0, 1.0], [0.25, 1.0, 0.0]]
"""
score_lists: list[list[float]] = []
for dlist, weight in zip(data_lists, weights):
mind = min(dlist)
maxd = max(dlist)
score: list[float] = []
# for weight 0 score is 1 - actual score
if weight == 0:
for item in dlist:
try:
score.append(1 - ((item - mind) / (maxd - mind)))
except ZeroDivisionError:
score.append(1)
elif weight == 1:
for item in dlist:
try:
score.append((item - mind) / (maxd - mind))
except ZeroDivisionError:
score.append(0)
# weight not 0 or 1
else:
msg = f"Invalid weight of {weight:f} provided"
raise ValueError(msg)
score_lists.append(score)
return score_lists
def generate_final_scores(score_lists: list[list[float]]) -> list[float]:
"""
>>> generate_final_scores([[1.0, 0.0, 0.33333333333333337],
... [0.75, 0.0, 1.0],
... [0.25, 1.0, 0.0]])
[2.0, 1.0, 1.3333333333333335]
"""
# initialize final scores
final_scores: list[float] = [0 for i in range(len(score_lists[0]))]
for slist in score_lists:
for j, ele in enumerate(slist):
final_scores[j] = final_scores[j] + ele
return final_scores
def procentual_proximity(
source_data: list[list[float]], weights: list[int]
) -> list[list[float]]:
"""
| `weights` - ``int`` list
| possible values - ``0`` / ``1``
* ``0`` if lower values have higher weight in the data set
* ``1`` if higher values have higher weight in the data set
>>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1])
[[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]]
"""
data_lists = get_data(source_data)
score_lists = calculate_each_score(data_lists, weights)
final_scores = generate_final_scores(score_lists)
# append scores to source data
for i, ele in enumerate(final_scores):
source_data[i].append(ele)
return source_data
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/greedy.py | other/greedy.py | class Things:
def __init__(self, name, value, weight):
self.name = name
self.value = value
self.weight = weight
def __repr__(self):
return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})"
def get_value(self):
return self.value
def get_name(self):
return self.name
def get_weight(self):
return self.weight
def value_weight(self):
return self.value / self.weight
def build_menu(name, value, weight):
menu = []
for i in range(len(value)):
menu.append(Things(name[i], value[i], weight[i]))
return menu
def greedy(item, max_cost, key_func):
items_copy = sorted(item, key=key_func, reverse=True)
result = []
total_value, total_cost = 0.0, 0.0
for i in range(len(items_copy)):
if (total_cost + items_copy[i].get_weight()) <= max_cost:
result.append(items_copy[i])
total_cost += items_copy[i].get_weight()
total_value += items_copy[i].get_value()
return (result, total_value)
def test_greedy():
"""
>>> food = ["Burger", "Pizza", "Coca Cola", "Rice",
... "Sambhar", "Chicken", "Fries", "Milk"]
>>> value = [80, 100, 60, 70, 50, 110, 90, 60]
>>> weight = [40, 60, 40, 70, 100, 85, 55, 70]
>>> foods = build_menu(food, value, weight)
>>> foods # doctest: +NORMALIZE_WHITESPACE
[Things(Burger, 80, 40), Things(Pizza, 100, 60), Things(Coca Cola, 60, 40),
Things(Rice, 70, 70), Things(Sambhar, 50, 100), Things(Chicken, 110, 85),
Things(Fries, 90, 55), Things(Milk, 60, 70)]
>>> greedy(foods, 500, Things.get_value) # doctest: +NORMALIZE_WHITESPACE
([Things(Chicken, 110, 85), Things(Pizza, 100, 60), Things(Fries, 90, 55),
Things(Burger, 80, 40), Things(Rice, 70, 70), Things(Coca Cola, 60, 40),
Things(Milk, 60, 70)], 570.0)
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/doomsday.py | other/doomsday.py | #!/bin/python3
# Doomsday algorithm info: https://en.wikipedia.org/wiki/Doomsday_rule
DOOMSDAY_LEAP = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
DOOMSDAY_NOT_LEAP = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5]
WEEK_DAY_NAMES = {
0: "Sunday",
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
}
def get_week_day(year: int, month: int, day: int) -> str:
"""Returns the week-day name out of a given date.
>>> get_week_day(2020, 10, 24)
'Saturday'
>>> get_week_day(2017, 10, 24)
'Tuesday'
>>> get_week_day(2019, 5, 3)
'Friday'
>>> get_week_day(1970, 9, 16)
'Wednesday'
>>> get_week_day(1870, 8, 13)
'Saturday'
>>> get_week_day(2040, 3, 14)
'Wednesday'
"""
# minimal input check:
assert len(str(year)) > 2, "year should be in YYYY format"
assert 1 <= month <= 12, "month should be between 1 to 12"
assert 1 <= day <= 31, "day should be between 1 to 31"
# Doomsday algorithm:
century = year // 100
century_anchor = (5 * (century % 4) + 2) % 7
centurian = year % 100
centurian_m = centurian % 12
dooms_day = (
(centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor
) % 7
day_anchor = (
DOOMSDAY_NOT_LEAP[month - 1]
if year % 4 != 0 or (centurian == 0 and year % 400 != 0)
else DOOMSDAY_LEAP[month - 1]
)
week_day = (dooms_day + day - day_anchor) % 7
return WEEK_DAY_NAMES[week_day]
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/__init__.py | other/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/lru_cache.py | other/lru_cache.py | from __future__ import annotations
from collections.abc import Callable
from typing import TypeVar
T = TypeVar("T")
U = TypeVar("U")
class DoubleLinkedListNode[T, U]:
"""
Double Linked List Node built specifically for LRU Cache
>>> DoubleLinkedListNode(1,1)
Node: key: 1, val: 1, has next: False, has prev: False
"""
def __init__(self, key: T | None, val: U | None):
self.key = key
self.val = val
self.next: DoubleLinkedListNode[T, U] | None = None
self.prev: DoubleLinkedListNode[T, U] | None = None
def __repr__(self) -> str:
return (
f"Node: key: {self.key}, val: {self.val}, "
f"has next: {bool(self.next)}, has prev: {bool(self.prev)}"
)
class DoubleLinkedList[T, U]:
"""
Double Linked List built specifically for LRU Cache
>>> dll: DoubleLinkedList = DoubleLinkedList()
>>> dll
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: None, val: None, has next: False, has prev: True
>>> first_node = DoubleLinkedListNode(1,10)
>>> first_node
Node: key: 1, val: 10, has next: False, has prev: False
>>> dll.add(first_node)
>>> dll
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: 1, val: 10, has next: True, has prev: True,
Node: key: None, val: None, has next: False, has prev: True
>>> # node is mutated
>>> first_node
Node: key: 1, val: 10, has next: True, has prev: True
>>> second_node = DoubleLinkedListNode(2,20)
>>> second_node
Node: key: 2, val: 20, has next: False, has prev: False
>>> dll.add(second_node)
>>> dll
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: 1, val: 10, has next: True, has prev: True,
Node: key: 2, val: 20, has next: True, has prev: True,
Node: key: None, val: None, has next: False, has prev: True
>>> removed_node = dll.remove(first_node)
>>> assert removed_node == first_node
>>> dll
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: 2, val: 20, has next: True, has prev: True,
Node: key: None, val: None, has next: False, has prev: True
>>> # Attempt to remove node not on list
>>> removed_node = dll.remove(first_node)
>>> removed_node is None
True
>>> # Attempt to remove head or rear
>>> dll.head
Node: key: None, val: None, has next: True, has prev: False
>>> dll.remove(dll.head) is None
True
>>> # Attempt to remove head or rear
>>> dll.rear
Node: key: None, val: None, has next: False, has prev: True
>>> dll.remove(dll.rear) is None
True
"""
def __init__(self) -> None:
self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None)
self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None)
self.head.next, self.rear.prev = self.rear, self.head
def __repr__(self) -> str:
rep = ["DoubleLinkedList"]
node = self.head
while node.next is not None:
rep.append(str(node))
node = node.next
rep.append(str(self.rear))
return ",\n ".join(rep)
def add(self, node: DoubleLinkedListNode[T, U]) -> None:
"""
Adds the given node to the end of the list (before rear)
"""
previous = self.rear.prev
# All nodes other than self.head are guaranteed to have non-None previous
assert previous is not None
previous.next = node
node.prev = previous
self.rear.prev = node
node.next = self.rear
def remove(
self, node: DoubleLinkedListNode[T, U]
) -> DoubleLinkedListNode[T, U] | None:
"""
Removes and returns the given node from the list
Returns None if node.prev or node.next is None
"""
if node.prev is None or node.next is None:
return None
node.prev.next = node.next
node.next.prev = node.prev
node.prev = None
node.next = None
return node
class LRUCache[T, U]:
"""
LRU Cache to store a given capacity of data. Can be used as a stand-alone object
or as a function decorator.
>>> cache = LRUCache(2)
>>> cache.put(1, 1)
>>> cache.put(2, 2)
>>> cache.get(1)
1
>>> cache.list
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: 2, val: 2, has next: True, has prev: True,
Node: key: 1, val: 1, has next: True, has prev: True,
Node: key: None, val: None, has next: False, has prev: True
>>> cache.cache # doctest: +NORMALIZE_WHITESPACE
{1: Node: key: 1, val: 1, has next: True, has prev: True, \
2: Node: key: 2, val: 2, has next: True, has prev: True}
>>> cache.put(3, 3)
>>> cache.list
DoubleLinkedList,
Node: key: None, val: None, has next: True, has prev: False,
Node: key: 1, val: 1, has next: True, has prev: True,
Node: key: 3, val: 3, has next: True, has prev: True,
Node: key: None, val: None, has next: False, has prev: True
>>> cache.cache # doctest: +NORMALIZE_WHITESPACE
{1: Node: key: 1, val: 1, has next: True, has prev: True, \
3: Node: key: 3, val: 3, has next: True, has prev: True}
>>> cache.get(2) is None
True
>>> cache.put(4, 4)
>>> cache.get(1) is None
True
>>> cache.get(3)
3
>>> cache.get(4)
4
>>> cache
CacheInfo(hits=3, misses=2, capacity=2, current size=2)
>>> @LRUCache.decorator(100)
... def fib(num):
... if num in (1, 2):
... return 1
... return fib(num - 1) + fib(num - 2)
>>> for i in range(1, 100):
... res = fib(i)
>>> fib.cache_info()
CacheInfo(hits=194, misses=99, capacity=100, current size=99)
"""
def __init__(self, capacity: int):
self.list: DoubleLinkedList[T, U] = DoubleLinkedList()
self.capacity = capacity
self.num_keys = 0
self.hits = 0
self.miss = 0
self.cache: dict[T, DoubleLinkedListNode[T, U]] = {}
def __repr__(self) -> str:
"""
Return the details for the cache instance
[hits, misses, capacity, current_size]
"""
return (
f"CacheInfo(hits={self.hits}, misses={self.miss}, "
f"capacity={self.capacity}, current size={self.num_keys})"
)
def __contains__(self, key: T) -> bool:
"""
>>> cache = LRUCache(1)
>>> 1 in cache
False
>>> cache.put(1, 1)
>>> 1 in cache
True
"""
return key in self.cache
def get(self, key: T) -> U | None:
"""
Returns the value for the input key and updates the Double Linked List.
Returns None if key is not present in cache
"""
# Note: pythonic interface would throw KeyError rather than return None
if key in self.cache:
self.hits += 1
value_node: DoubleLinkedListNode[T, U] = self.cache[key]
node = self.list.remove(self.cache[key])
assert node == value_node
# node is guaranteed not None because it is in self.cache
assert node is not None
self.list.add(node)
return node.val
self.miss += 1
return None
def put(self, key: T, value: U) -> None:
"""
Sets the value for the input key and updates the Double Linked List
"""
if key not in self.cache:
if self.num_keys >= self.capacity:
# delete first node (oldest) when over capacity
first_node = self.list.head.next
# guaranteed to have a non-None first node when num_keys > 0
# explain to type checker via assertions
assert first_node is not None
assert first_node.key is not None
assert (
self.list.remove(first_node) is not None
) # node guaranteed to be in list assert node.key is not None
del self.cache[first_node.key]
self.num_keys -= 1
self.cache[key] = DoubleLinkedListNode(key, value)
self.list.add(self.cache[key])
self.num_keys += 1
else:
# bump node to the end of the list, update value
node = self.list.remove(self.cache[key])
assert node is not None # node guaranteed to be in list
node.val = value
self.list.add(node)
@classmethod
def decorator(
cls, size: int = 128
) -> Callable[[Callable[[T], U]], Callable[..., U]]:
"""
Decorator version of LRU Cache
Decorated function must be function of T -> U
"""
def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]:
# variable to map the decorator functions to their respective instance
decorator_function_to_instance_map: dict[
Callable[[T], U], LRUCache[T, U]
] = {}
def cache_decorator_wrapper(*args: T) -> U:
if func not in decorator_function_to_instance_map:
decorator_function_to_instance_map[func] = LRUCache(size)
result = decorator_function_to_instance_map[func].get(args[0])
if result is None:
result = func(*args)
decorator_function_to_instance_map[func].put(args[0], result)
return result
def cache_info() -> LRUCache[T, U]:
return decorator_function_to_instance_map[func]
setattr(cache_decorator_wrapper, "cache_info", cache_info) # noqa: B010
return cache_decorator_wrapper
return cache_decorator_inner
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/graham_scan.py | other/graham_scan.py | """
This is a pure Python implementation of the Graham scan algorithm
Source: https://en.wikipedia.org/wiki/Graham_scan
For doctests run following command:
python3 -m doctest -v graham_scan.py
"""
from __future__ import annotations
from collections import deque
from enum import Enum
from math import atan2, degrees
from sys import maxsize
# traversal from the lowest and the most left point in anti-clockwise direction
# if direction gets right, the previous point is not the convex hull.
class Direction(Enum):
left = 1
straight = 2
right = 3
def __repr__(self):
return f"{self.__class__.__name__}.{self.name}"
def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float:
"""Return the angle toward to point from (minx, miny)
:param point: The target point
minx: The starting point's x
miny: The starting point's y
:return: the angle
Examples:
>>> angle_comparer((1,1), 0, 0)
45.0
>>> angle_comparer((100,1), 10, 10)
-5.710593137499642
>>> angle_comparer((5,5), 2, 3)
33.690067525979785
"""
# sort the points accorgind to the angle from the lowest and the most left point
x, y = point
return degrees(atan2(y - miny, x - minx))
def check_direction(
starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int]
) -> Direction:
"""Return the direction toward to the line from via to target from starting
:param starting: The starting point
via: The via point
target: The target point
:return: the Direction
Examples:
>>> check_direction((1,1), (2,2), (3,3))
Direction.straight
>>> check_direction((60,1), (-50,199), (30,2))
Direction.left
>>> check_direction((0,0), (5,5), (10,0))
Direction.right
"""
x0, y0 = starting
x1, y1 = via
x2, y2 = target
via_angle = degrees(atan2(y1 - y0, x1 - x0))
via_angle %= 360
target_angle = degrees(atan2(y2 - y0, x2 - x0))
target_angle %= 360
# t-
# \ \
# \ v
# \|
# s
# via_angle is always lower than target_angle, if direction is left.
# If they are same, it means they are on a same line of convex hull.
if target_angle > via_angle:
return Direction.left
elif target_angle == via_angle:
return Direction.straight
else:
return Direction.right
def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Pure implementation of graham scan algorithm in Python
:param points: The unique points on coordinates.
:return: The points on convex hell.
Examples:
>>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)])
[(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)]
>>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)])
[(0, 0), (1, 0), (1, 1), (0, 1)]
>>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)])
[(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]
>>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)])
[(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)]
"""
if len(points) <= 2:
# There is no convex hull
raise ValueError("graham_scan: argument must contain more than 3 points.")
if len(points) == 3:
return points
# find the lowest and the most left point
minidx = 0
miny, minx = maxsize, maxsize
for i, point in enumerate(points):
x = point[0]
y = point[1]
if y < miny:
miny = y
minx = x
minidx = i
if y == miny and x < minx:
minx = x
minidx = i
# remove the lowest and the most left point from points for preparing for sort
points.pop(minidx)
sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny))
# This insert actually costs complexity,
# and you should instead add (minx, miny) into stack later.
# I'm using insert just for easy understanding.
sorted_points.insert(0, (minx, miny))
stack: deque[tuple[int, int]] = deque()
stack.append(sorted_points[0])
stack.append(sorted_points[1])
stack.append(sorted_points[2])
# The first 3 points lines are towards the left because we sort them by their angle
# from minx, miny.
current_direction = Direction.left
for i in range(3, len(sorted_points)):
while True:
starting = stack[-2]
via = stack[-1]
target = sorted_points[i]
next_direction = check_direction(starting, via, target)
if next_direction == Direction.left:
current_direction = Direction.left
break
if next_direction == Direction.straight:
if current_direction == Direction.left:
# We keep current_direction as left.
# Because if the straight line keeps as straight,
# we want to know if this straight line is towards left.
break
elif current_direction == Direction.right:
# If the straight line is towards right,
# every previous points on that straight line is not convex hull.
stack.pop()
if next_direction == Direction.right:
stack.pop()
stack.append(sorted_points[i])
return list(stack)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/activity_selection.py | other/activity_selection.py | """The following implementation assumes that the activities
are already sorted according to their finish time"""
"""Prints a maximum set of activities that can be done by a
single person, one at a time"""
# n --> Total number of activities
# start[]--> An array that contains start time of all activities
# finish[] --> An array that contains finish time of all activities
def print_max_activities(start: list[int], finish: list[int]) -> None:
"""
>>> start = [1, 3, 0, 5, 8, 5]
>>> finish = [2, 4, 6, 7, 9, 9]
>>> print_max_activities(start, finish)
The following activities are selected:
0,1,3,4,
"""
n = len(finish)
print("The following activities are selected:")
# The first activity is always selected
i = 0
print(i, end=",")
# Consider rest of the activities
for j in range(n):
# If this activity has start time greater than
# or equal to the finish time of previously
# selected activity, then select it
if start[j] >= finish[i]:
print(j, end=",")
i = j
if __name__ == "__main__":
import doctest
doctest.testmod()
start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9]
print_max_activities(start, finish)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/number_container_system.py | other/number_container_system.py | """
A number container system that uses binary search to delete and insert values into
arrays with O(log n) write times and O(1) read times.
This container system holds integers at indexes.
Further explained in this leetcode problem
> https://leetcode.com/problems/minimum-cost-tree-from-leaf-values
"""
class NumberContainer:
def __init__(self) -> None:
# numbermap keys are the number and its values are lists of indexes sorted
# in ascending order
self.numbermap: dict[int, list[int]] = {}
# indexmap keys are an index and it's values are the number at that index
self.indexmap: dict[int, int] = {}
def binary_search_delete(self, array: list | str | range, item: int) -> list[int]:
"""
Removes the item from the sorted array and returns
the new array.
>>> NumberContainer().binary_search_delete([1,2,3], 2)
[1, 3]
>>> NumberContainer().binary_search_delete([0, 0, 0], 0)
[0, 0]
>>> NumberContainer().binary_search_delete([-1, -1, -1], -1)
[-1, -1]
>>> NumberContainer().binary_search_delete([-1, 0], 0)
[-1]
>>> NumberContainer().binary_search_delete([-1, 0], -1)
[0]
>>> NumberContainer().binary_search_delete(range(7), 3)
[0, 1, 2, 4, 5, 6]
>>> NumberContainer().binary_search_delete([1.1, 2.2, 3.3], 2.2)
[1.1, 3.3]
>>> NumberContainer().binary_search_delete("abcde", "c")
['a', 'b', 'd', 'e']
>>> NumberContainer().binary_search_delete([0, -1, 2, 4], 0)
Traceback (most recent call last):
...
ValueError: Either the item is not in the array or the array was unsorted
>>> NumberContainer().binary_search_delete([2, 0, 4, -1, 11], -1)
Traceback (most recent call last):
...
ValueError: Either the item is not in the array or the array was unsorted
>>> NumberContainer().binary_search_delete(125, 1)
Traceback (most recent call last):
...
TypeError: binary_search_delete() only accepts either a list, range or str
"""
if isinstance(array, (range, str)):
array = list(array)
elif not isinstance(array, list):
raise TypeError(
"binary_search_delete() only accepts either a list, range or str"
)
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == item:
array.pop(mid)
return array
elif array[mid] < item:
low = mid + 1
else:
high = mid - 1
raise ValueError(
"Either the item is not in the array or the array was unsorted"
)
def binary_search_insert(self, array: list | str | range, index: int) -> list[int]:
"""
Inserts the index into the sorted array
at the correct position.
>>> NumberContainer().binary_search_insert([1,2,3], 2)
[1, 2, 2, 3]
>>> NumberContainer().binary_search_insert([0,1,3], 2)
[0, 1, 2, 3]
>>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 103], 51)
[-5, -3, 0, 0, 11, 51, 103]
>>> NumberContainer().binary_search_insert([-5, -3, 0, 0, 11, 100, 103], 101)
[-5, -3, 0, 0, 11, 100, 101, 103]
>>> NumberContainer().binary_search_insert(range(10), 4)
[0, 1, 2, 3, 4, 4, 5, 6, 7, 8, 9]
>>> NumberContainer().binary_search_insert("abd", "c")
['a', 'b', 'c', 'd']
>>> NumberContainer().binary_search_insert(131, 23)
Traceback (most recent call last):
...
TypeError: binary_search_insert() only accepts either a list, range or str
"""
if isinstance(array, (range, str)):
array = list(array)
elif not isinstance(array, list):
raise TypeError(
"binary_search_insert() only accepts either a list, range or str"
)
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == index:
# If the item already exists in the array,
# insert it after the existing item
array.insert(mid + 1, index)
return array
elif array[mid] < index:
low = mid + 1
else:
high = mid - 1
# If the item doesn't exist in the array, insert it at the appropriate position
array.insert(low, index)
return array
def change(self, index: int, number: int) -> None:
"""
Changes (sets) the index as number
>>> cont = NumberContainer()
>>> cont.change(0, 10)
>>> cont.change(0, 20)
>>> cont.change(-13, 20)
>>> cont.change(-100030, 20032903290)
"""
# Remove previous index
if index in self.indexmap:
n = self.indexmap[index]
if len(self.numbermap[n]) == 1:
del self.numbermap[n]
else:
self.numbermap[n] = self.binary_search_delete(self.numbermap[n], index)
# Set new index
self.indexmap[index] = number
# Number not seen before or empty so insert number value
if number not in self.numbermap:
self.numbermap[number] = [index]
# Here we need to perform a binary search insertion in order to insert
# The item in the correct place
else:
self.numbermap[number] = self.binary_search_insert(
self.numbermap[number], index
)
def find(self, number: int) -> int:
"""
Returns the smallest index where the number is.
>>> cont = NumberContainer()
>>> cont.find(10)
-1
>>> cont.change(0, 10)
>>> cont.find(10)
0
>>> cont.change(0, 20)
>>> cont.find(10)
-1
>>> cont.find(20)
0
"""
# Simply return the 0th index (smallest) of the indexes found (or -1)
return self.numbermap.get(number, [-1])[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/other/fischer_yates_shuffle.py | other/fischer_yates_shuffle.py | #!/usr/bin/python
"""
The Fisher-Yates shuffle is an algorithm for generating a random permutation of a
finite sequence.
For more details visit
wikipedia/Fischer-Yates-Shuffle.
"""
import random
from typing import Any
def fisher_yates_shuffle(data: list) -> list[Any]:
for _ in range(len(data)):
a = random.randint(0, len(data) - 1)
b = random.randint(0, len(data) - 1)
data[a], data[b] = data[b], data[a]
return data
if __name__ == "__main__":
integers = [0, 1, 2, 3, 4, 5, 6, 7]
strings = ["python", "says", "hello", "!"]
print("Fisher-Yates Shuffle:")
print("List", integers, strings)
print("FY Shuffle", fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/julia_sets.py | fractals/julia_sets.py | """Author Alexandre De Zotti
Draws Julia sets of quadratic polynomials and exponential maps.
More specifically, this iterates the function a fixed number of times
then plots whether the absolute value of the last iterate is greater than
a fixed threshold (named "escape radius"). For the exponential map this is not
really an escape radius but rather a convenient way to approximate the Julia
set with bounded orbits.
The examples presented here are:
- The Cauliflower Julia set, see e.g.
https://en.wikipedia.org/wiki/File:Julia_z2%2B0,25.png
- Other examples from https://en.wikipedia.org/wiki/Julia_set
- An exponential map Julia set, ambiantly homeomorphic to the examples in
https://www.math.univ-toulouse.fr/~cheritat/GalII/galery.html
and
https://ddd.uab.cat/pub/pubmat/02141493v43n1/02141493v43n1p27.pdf
Remark: Some overflow runtime warnings are suppressed. This is because of the
way the iteration loop is implemented, using numpy's efficient computations.
Overflows and infinites are replaced after each step by a large number.
"""
import warnings
from collections.abc import Callable
from typing import Any
import matplotlib.pyplot as plt
import numpy as np
c_cauliflower = 0.25 + 0.0j
c_polynomial_1 = -0.4 + 0.6j
c_polynomial_2 = -0.1 + 0.651j
c_exponential = -2.0
nb_iterations = 56
window_size = 2.0
nb_pixels = 666
def eval_exponential(c_parameter: complex, z_values: np.ndarray) -> np.ndarray:
"""
Evaluate $e^z + c$.
>>> float(eval_exponential(0, 0))
1.0
>>> bool(abs(eval_exponential(1, np.pi*1.j)) < 1e-15)
True
>>> bool(abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15)
True
"""
return np.exp(z_values) + c_parameter
def eval_quadratic_polynomial(c_parameter: complex, z_values: np.ndarray) -> np.ndarray:
"""
>>> eval_quadratic_polynomial(0, 2)
4
>>> eval_quadratic_polynomial(-1, 1)
0
>>> round(eval_quadratic_polynomial(1.j, 0).imag)
1
>>> round(eval_quadratic_polynomial(1.j, 0).real)
0
"""
return z_values * z_values + c_parameter
def prepare_grid(window_size: float, nb_pixels: int) -> np.ndarray:
"""
Create a grid of complex values of size nb_pixels*nb_pixels with real and
imaginary parts ranging from -window_size to window_size (inclusive).
Returns a numpy array.
>>> prepare_grid(1,3)
array([[-1.-1.j, -1.+0.j, -1.+1.j],
[ 0.-1.j, 0.+0.j, 0.+1.j],
[ 1.-1.j, 1.+0.j, 1.+1.j]])
"""
x = np.linspace(-window_size, window_size, nb_pixels)
x = x.reshape((nb_pixels, 1))
y = np.linspace(-window_size, window_size, nb_pixels)
y = y.reshape((1, nb_pixels))
return x + 1.0j * y
def iterate_function(
eval_function: Callable[[Any, np.ndarray], np.ndarray],
function_params: Any,
nb_iterations: int,
z_0: np.ndarray,
infinity: float | None = None,
) -> np.ndarray:
"""
Iterate the function "eval_function" exactly nb_iterations times.
The first argument of the function is a parameter which is contained in
function_params. The variable z_0 is an array that contains the initial
values to iterate from.
This function returns the final iterates.
>>> iterate_function(eval_quadratic_polynomial, 0, 3, np.array([0,1,2])).shape
(3,)
>>> complex(np.round(iterate_function(eval_quadratic_polynomial,
... 0,
... 3,
... np.array([0,1,2]))[0]))
0j
>>> complex(np.round(iterate_function(eval_quadratic_polynomial,
... 0,
... 3,
... np.array([0,1,2]))[1]))
(1+0j)
>>> complex(np.round(iterate_function(eval_quadratic_polynomial,
... 0,
... 3,
... np.array([0,1,2]))[2]))
(256+0j)
"""
z_n = z_0.astype("complex64")
for _ in range(nb_iterations):
z_n = eval_function(function_params, z_n)
if infinity is not None:
np.nan_to_num(z_n, copy=False, nan=infinity)
z_n[abs(z_n) == np.inf] = infinity
return z_n
def show_results(
function_label: str,
function_params: Any,
escape_radius: float,
z_final: np.ndarray,
) -> None:
"""
Plots of whether the absolute value of z_final is greater than
the value of escape_radius. Adds the function_label and function_params to
the title.
>>> show_results('80', 0, 1, np.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]]))
"""
abs_z_final = (abs(z_final)).transpose()
abs_z_final[:, :] = abs_z_final[::-1, :]
plt.matshow(abs_z_final < escape_radius)
plt.title(f"Julia set of ${function_label}$, $c={function_params}$")
plt.show()
def ignore_overflow_warnings() -> None:
"""
Ignore some overflow and invalid value warnings.
>>> ignore_overflow_warnings()
"""
warnings.filterwarnings(
"ignore", category=RuntimeWarning, message="overflow encountered in multiply"
)
warnings.filterwarnings(
"ignore",
category=RuntimeWarning,
message="invalid value encountered in multiply",
)
warnings.filterwarnings(
"ignore", category=RuntimeWarning, message="overflow encountered in absolute"
)
warnings.filterwarnings(
"ignore", category=RuntimeWarning, message="overflow encountered in exp"
)
if __name__ == "__main__":
z_0 = prepare_grid(window_size, nb_pixels)
ignore_overflow_warnings() # See file header for explanations
nb_iterations = 24
escape_radius = 2 * abs(c_cauliflower) + 1
z_final = iterate_function(
eval_quadratic_polynomial,
c_cauliflower,
nb_iterations,
z_0,
infinity=1.1 * escape_radius,
)
show_results("z^2+c", c_cauliflower, escape_radius, z_final)
nb_iterations = 64
escape_radius = 2 * abs(c_polynomial_1) + 1
z_final = iterate_function(
eval_quadratic_polynomial,
c_polynomial_1,
nb_iterations,
z_0,
infinity=1.1 * escape_radius,
)
show_results("z^2+c", c_polynomial_1, escape_radius, z_final)
nb_iterations = 161
escape_radius = 2 * abs(c_polynomial_2) + 1
z_final = iterate_function(
eval_quadratic_polynomial,
c_polynomial_2,
nb_iterations,
z_0,
infinity=1.1 * escape_radius,
)
show_results("z^2+c", c_polynomial_2, escape_radius, z_final)
nb_iterations = 12
escape_radius = 10000.0
z_final = iterate_function(
eval_exponential,
c_exponential,
nb_iterations,
z_0 + 2,
infinity=1.0e10,
)
show_results("e^z+c", c_exponential, escape_radius, z_final)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/mandelbrot.py | fractals/mandelbrot.py | """
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""
import colorsys
from PIL import Image
def get_distance(x: float, y: float, max_step: int) -> float:
"""
Return the relative distance (= step/max_step) after which the complex number
constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
diverge so their distance is 1.
>>> get_distance(0, 0, 50)
1.0
>>> get_distance(0.5, 0.5, 50)
0.061224489795918366
>>> get_distance(2, 0, 50)
0.0
"""
a = x
b = y
for step in range(max_step): # noqa: B007
a_new = a * a - b * b + x
b = 2 * a * b + y
a = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Black&white color-coding that ignores the relative distance. The Mandelbrot
set is black, everything else is white.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def get_color_coded_rgb(distance: float) -> tuple:
"""
Color-coding taking the relative distance into account. The Mandelbrot set
is black.
>>> get_color_coded_rgb(0)
(255, 0, 0)
>>> get_color_coded_rgb(0.5)
(0, 255, 255)
>>> get_color_coded_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))
def get_image(
image_width: int = 800,
image_height: int = 600,
figure_center_x: float = -0.6,
figure_center_y: float = 0,
figure_width: float = 3.2,
max_step: int = 50,
use_distance_color_coding: bool = True,
) -> Image.Image:
"""
Function to generate the image of the Mandelbrot set. Two types of coordinates
are used: image-coordinates that refer to the pixels and figure-coordinates
that refer to the complex numbers inside and outside the Mandelbrot set. The
figure-coordinates in the arguments of this function determine which section
of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
Commenting out tests that slow down pytest...
# 13.35s call fractals/mandelbrot.py::mandelbrot.get_image
# >>> get_image().load()[0,0]
(255, 0, 0)
# >>> get_image(use_distance_color_coding = False).load()[0,0]
(255, 255, 255)
"""
img = Image.new("RGB", (image_width, image_height))
pixels = img.load()
# loop through the image-coordinates
for image_x in range(image_width):
for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height
distance = get_distance(figure_x, figure_y, max_step)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
pixels[image_x, image_y] = get_color_coded_rgb(distance)
else:
pixels[image_x, image_y] = get_black_and_white_rgb(distance)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
img = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/sierpinski_triangle.py | fractals/sierpinski_triangle.py | """
Author Anurag Kumar | anuragkumarak95@gmail.com | git/anuragkumarak95
Simple example of fractal generation using recursion.
What is the Sierpiński Triangle?
The Sierpiński triangle (sometimes spelled Sierpinski), also called the
Sierpiński gasket or Sierpiński sieve, is a fractal attractive fixed set with
the overall shape of an equilateral triangle, subdivided recursively into
smaller equilateral triangles. Originally constructed as a curve, this is one of
the basic examples of self-similar sets—that is, it is a mathematically
generated pattern that is reproducible at any magnification or reduction. It is
named after the Polish mathematician Wacław Sierpiński, but appeared as a
decorative pattern many centuries before the work of Sierpiński.
Usage: python sierpinski_triangle.py <int:depth_for_fractal>
Credits:
The above description is taken from
https://en.wikipedia.org/wiki/Sierpi%C5%84ski_triangle
This code was written by editing the code from
https://www.riannetrujillo.com/blog/python-fractal/
"""
import sys
import turtle
def get_mid(p1: tuple[float, float], p2: tuple[float, float]) -> tuple[float, float]:
"""
Find the midpoint of two points
>>> get_mid((0, 0), (2, 2))
(1.0, 1.0)
>>> get_mid((-3, -3), (3, 3))
(0.0, 0.0)
>>> get_mid((1, 0), (3, 2))
(2.0, 1.0)
>>> get_mid((0, 0), (1, 1))
(0.5, 0.5)
>>> get_mid((0, 0), (0, 0))
(0.0, 0.0)
"""
return (p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2
def triangle(
vertex1: tuple[float, float],
vertex2: tuple[float, float],
vertex3: tuple[float, float],
depth: int,
) -> None:
"""
Recursively draw the Sierpinski triangle given the vertices of the triangle
and the recursion depth
"""
my_pen.up()
my_pen.goto(vertex1[0], vertex1[1])
my_pen.down()
my_pen.goto(vertex2[0], vertex2[1])
my_pen.goto(vertex3[0], vertex3[1])
my_pen.goto(vertex1[0], vertex1[1])
if depth == 0:
return
triangle(vertex1, get_mid(vertex1, vertex2), get_mid(vertex1, vertex3), depth - 1)
triangle(vertex2, get_mid(vertex1, vertex2), get_mid(vertex2, vertex3), depth - 1)
triangle(vertex3, get_mid(vertex3, vertex2), get_mid(vertex1, vertex3), depth - 1)
if __name__ == "__main__":
if len(sys.argv) != 2:
raise ValueError(
"Correct format for using this script: "
"python fractals.py <int:depth_for_fractal>"
)
my_pen = turtle.Turtle()
my_pen.ht()
my_pen.speed(5)
my_pen.pencolor("red")
vertices = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle
triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
turtle.Screen().exitonclick()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/__init__.py | fractals/__init__.py | python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false | |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/koch_snowflake.py | fractals/koch_snowflake.py | """
Description
The Koch snowflake is a fractal curve and one of the earliest fractals to
have been described. The Koch snowflake can be built up iteratively, in a
sequence of stages. The first stage is an equilateral triangle, and each
successive stage is formed by adding outward bends to each side of the
previous stage, making smaller equilateral triangles.
This can be achieved through the following steps for each line:
1. divide the line segment into three segments of equal length.
2. draw an equilateral triangle that has the middle segment from step 1
as its base and points outward.
3. remove the line segment that is the base of the triangle from step 2.
(description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
(for a more detailed explanation and an implementation in the
Processing language, see https://natureofcode.com/book/chapter-8-fractals/
#84-the-koch-curve-and-the-arraylist-technique )
Requirements (pip):
- matplotlib
- numpy
"""
from __future__ import annotations
import matplotlib.pyplot as plt
import numpy as np
# initial triangle of Koch snowflake
VECTOR_1 = np.array([0, 0])
VECTOR_2 = np.array([0.5, 0.8660254])
VECTOR_3 = np.array([1, 0])
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
# uncomment for simple Koch curve instead of Koch snowflake
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
def iterate(initial_vectors: list[np.ndarray], steps: int) -> list[np.ndarray]:
"""
Go through the number of iterations determined by the argument "steps".
Be careful with high values (above 5) since the time to calculate increases
exponentially.
>>> iterate([np.array([0, 0]), np.array([1, 0])], 1)
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
vectors = initial_vectors
for _ in range(steps):
vectors = iteration_step(vectors)
return vectors
def iteration_step(vectors: list[np.ndarray]) -> list[np.ndarray]:
"""
Loops through each pair of adjacent vectors. Each line between two adjacent
vectors is divided into 4 segments by adding 3 additional vectors in-between
the original two vectors. The vector in the middle is constructed through a
60 degree rotation so it is bent outwards.
>>> iteration_step([np.array([0, 0]), np.array([1, 0])])
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
new_vectors = []
for i, start_vector in enumerate(vectors[:-1]):
end_vector = vectors[i + 1]
new_vectors.append(start_vector)
difference_vector = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3)
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60)
)
new_vectors.append(start_vector + difference_vector * 2 / 3)
new_vectors.append(vectors[-1])
return new_vectors
def rotate(vector: np.ndarray, angle_in_degrees: float) -> np.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(np.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(np.array([1, 0]), 90)
array([6.123234e-17, 1.000000e+00])
"""
theta = np.radians(angle_in_degrees)
c, s = np.cos(theta), np.sin(theta)
rotation_matrix = np.array(((c, -s), (s, c)))
return np.dot(rotation_matrix, vector)
def plot(vectors: list[np.ndarray]) -> None:
"""
Utility function to plot the vectors using matplotlib.pyplot
No doctest was implemented since this function does not have a return value
"""
# avoid stretched display of graph
axes = plt.gca()
axes.set_aspect("equal")
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
x_coordinates, y_coordinates = zip(*vectors)
plt.plot(x_coordinates, y_coordinates)
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
processed_vectors = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
TheAlgorithms/Python | https://github.com/TheAlgorithms/Python/blob/2c15b8c54eb8130e83640fe1d911c10eb6cd70d4/fractals/vicsek.py | fractals/vicsek.py | """Authors Bastien Capiaux & Mehdi Oudghiri
The Vicsek fractal algorithm is a recursive algorithm that creates a
pattern known as the Vicsek fractal or the Vicsek square.
It is based on the concept of self-similarity, where the pattern at each
level of recursion resembles the overall pattern.
The algorithm involves dividing a square into 9 equal smaller squares,
removing the center square, and then repeating this process on the remaining 8 squares.
This results in a pattern that exhibits self-similarity and has a
square-shaped outline with smaller squares within it.
Source: https://en.wikipedia.org/wiki/Vicsek_fractal
"""
import turtle
def draw_cross(x: float, y: float, length: float):
"""
Draw a cross at the specified position and with the specified length.
"""
turtle.up()
turtle.goto(x - length / 2, y - length / 6)
turtle.down()
turtle.seth(0)
turtle.begin_fill()
for _ in range(4):
turtle.fd(length / 3)
turtle.right(90)
turtle.fd(length / 3)
turtle.left(90)
turtle.fd(length / 3)
turtle.left(90)
turtle.end_fill()
def draw_fractal_recursive(x: float, y: float, length: float, depth: float):
"""
Recursively draw the Vicsek fractal at the specified position, with the
specified length and depth.
"""
if depth == 0:
draw_cross(x, y, length)
return
draw_fractal_recursive(x, y, length / 3, depth - 1)
draw_fractal_recursive(x + length / 3, y, length / 3, depth - 1)
draw_fractal_recursive(x - length / 3, y, length / 3, depth - 1)
draw_fractal_recursive(x, y + length / 3, length / 3, depth - 1)
draw_fractal_recursive(x, y - length / 3, length / 3, depth - 1)
def set_color(rgb: str):
turtle.color(rgb)
def draw_vicsek_fractal(x: float, y: float, length: float, depth: float, color="blue"):
"""
Draw the Vicsek fractal at the specified position, with the specified
length and depth.
"""
turtle.speed(0)
turtle.hideturtle()
set_color(color)
draw_fractal_recursive(x, y, length, depth)
turtle.Screen().update()
def main():
draw_vicsek_fractal(0, 0, 800, 4)
turtle.done()
if __name__ == "__main__":
main()
| python | MIT | 2c15b8c54eb8130e83640fe1d911c10eb6cd70d4 | 2026-01-04T14:38:15.231112Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/run_evals.py | backend/run_evals.py | # Load environment variables first
from dotenv import load_dotenv
load_dotenv()
import asyncio
from evals.runner import run_image_evals
async def main():
await run_image_evals()
# async def text_main():
# OUTPUT_DIR = EVALS_DIR + "/outputs"
# GENERAL_TEXT_V1 = [
# "Login form",
# "Simple notification",
# "button",
# "saas dashboard",
# "landing page for barber shop",
# ]
# tasks: list[Coroutine[Any, Any, str]] = []
# for prompt in GENERAL_TEXT_V1:
# for n in range(N): # Generate N tasks for each input
# if n == 0:
# task = generate_code_for_text(
# text=prompt,
# stack=STACK,
# model=Llm.CLAUDE_4_5_SONNET_2025_09_29,
# )
# else:
# task = generate_code_for_text(
# text=prompt, stack=STACK, model=Llm.GPT_4O_2024_05_13
# )
# tasks.append(task)
# print(f"Generating {len(tasks)} codes")
# results = await asyncio.gather(*tasks)
# os.makedirs(OUTPUT_DIR, exist_ok=True)
# for i, content in enumerate(results):
# # Calculate index for filename and output number
# eval_index = i // N
# output_number = i % N
# filename = GENERAL_TEXT_V1[eval_index]
# # File name is derived from the original filename in evals with an added output number
# output_filename = f"{os.path.splitext(filename)[0]}_{output_number}.html"
# output_filepath = os.path.join(OUTPUT_DIR, output_filename)
# with open(output_filepath, "w") as file:
# file.write(content)
if __name__ == "__main__":
asyncio.run(main())
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/custom_types.py | backend/custom_types.py | from typing import Literal
InputMode = Literal[
"image",
"video",
"text",
]
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/run_image_generation_evals.py | backend/run_image_generation_evals.py | import asyncio
import os
from typing import List, Optional, Literal
from dotenv import load_dotenv
import aiohttp
from image_generation.core import process_tasks
EVALS = [
"Romantic Background",
"Company logo: A stylized green sprout emerging from a circle",
"Placeholder image of a PDF cover with abstract design",
"A complex bubble diagram showing various interconnected features and aspects of FestivalPro, with a large central bubble surrounded by smaller bubbles of different colors representing different categories and functionalities",
"A vibrant, abstract visualization of the RhythmRise experience ecosystem, featuring interconnected neon elements representing music, technology, and human connection",
"Banner with text 'LiblibAI学院 课程入口'",
"Profile picture of Pierre-Louis Labonne",
"Two hands holding iPhone 14 models with colorful displays",
"Portrait of a woman with long dark hair smiling at the camera",
"Threadless logo on a gradient background from light pink to coral",
"Jordan Schlansky Shows Conan His Favorite Nose Hair Trimmer",
"Team Coco",
"Intro to Large Language Models",
"Andrej Karpathy",
"He built a $200 million toy company",
"CNBC International",
"What will happen in year three of the war?",
"Channel",
"This is it",
"How ASML Dominates Chip Machines",
]
# Load environment variables
load_dotenv()
# Get API keys from environment variables
OPENAI_API_KEY: Optional[str] = os.getenv("OPENAI_API_KEY")
REPLICATE_API_TOKEN: Optional[str] = os.getenv("REPLICATE_API_TOKEN")
# Directory to save generated images
OUTPUT_DIR: str = "generated_images"
async def generate_and_save_images(
prompts: List[str],
model: Literal["dalle3", "flux"],
api_key: Optional[str],
) -> None:
# Ensure the output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
if api_key is None:
raise ValueError(f"API key for {model} is not set in the environment variables")
# Generate images
results: List[Optional[str]] = await process_tasks(
prompts, api_key, None, model=model
)
# Save images to disk
async with aiohttp.ClientSession() as session:
for i, image_url in enumerate(results):
if image_url:
# Get the image data
async with session.get(image_url) as response:
image_data: bytes = await response.read()
# Save the image with a filename based on the input eval
prefix = "replicate_" if model == "flux" else "dalle3_"
filename: str = (
f"{prefix}{prompts[i][:50].replace(' ', '_').replace(':', '')}.png"
)
filepath: str = os.path.join(OUTPUT_DIR, filename)
with open(filepath, "wb") as f:
f.write(image_data)
print(f"Saved {model} image: {filepath}")
else:
print(f"Failed to generate {model} image for prompt: {prompts[i]}")
async def main() -> None:
# await generate_and_save_images(EVALS, "dalle3", OPENAI_API_KEY)
await generate_and_save_images(EVALS, "flux", REPLICATE_API_TOKEN)
if __name__ == "__main__":
asyncio.run(main())
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/llm.py | backend/llm.py | from enum import Enum
from typing import TypedDict
# Actual model versions that are passed to the LLMs and stored in our logs
class Llm(Enum):
GPT_4_VISION = "gpt-4-vision-preview"
GPT_4_TURBO_2024_04_09 = "gpt-4-turbo-2024-04-09"
GPT_4O_2024_05_13 = "gpt-4o-2024-05-13"
GPT_4O_2024_08_06 = "gpt-4o-2024-08-06"
GPT_4O_2024_11_20 = "gpt-4o-2024-11-20"
GPT_4_1_2025_04_14 = "gpt-4.1-2025-04-14"
GPT_4_1_MINI_2025_04_14 = "gpt-4.1-mini-2025-04-14"
GPT_4_1_NANO_2025_04_14 = "gpt-4.1-nano-2025-04-14"
CLAUDE_3_SONNET = "claude-3-sonnet-20240229"
CLAUDE_3_OPUS = "claude-3-opus-20240229"
CLAUDE_3_HAIKU = "claude-3-haiku-20240307"
CLAUDE_3_7_SONNET_2025_02_19 = "claude-3-7-sonnet-20250219"
CLAUDE_4_SONNET_2025_05_14 = "claude-sonnet-4-20250514"
CLAUDE_4_5_SONNET_2025_09_29 = "claude-sonnet-4-5-20250929"
CLAUDE_4_OPUS_2025_05_14 = "claude-opus-4-20250514"
GEMINI_2_0_FLASH_EXP = "gemini-2.0-flash-exp"
GEMINI_2_0_FLASH = "gemini-2.0-flash"
GEMINI_2_0_PRO_EXP = "gemini-2.0-pro-exp-02-05"
GEMINI_2_5_FLASH_PREVIEW_05_20 = "gemini-2.5-flash-preview-05-20"
O1_2024_12_17 = "o1-2024-12-17"
O4_MINI_2025_04_16 = "o4-mini-2025-04-16"
O3_2025_04_16 = "o3-2025-04-16"
class Completion(TypedDict):
duration: float
code: str
# Explicitly map each model to the provider backing it. This keeps provider
# groupings authoritative and avoids relying on name conventions when checking
# models elsewhere in the codebase.
MODEL_PROVIDER: dict[Llm, str] = {
# OpenAI models
Llm.GPT_4_VISION: "openai",
Llm.GPT_4_TURBO_2024_04_09: "openai",
Llm.GPT_4O_2024_05_13: "openai",
Llm.GPT_4O_2024_08_06: "openai",
Llm.GPT_4O_2024_11_20: "openai",
Llm.GPT_4_1_2025_04_14: "openai",
Llm.GPT_4_1_MINI_2025_04_14: "openai",
Llm.GPT_4_1_NANO_2025_04_14: "openai",
Llm.O1_2024_12_17: "openai",
Llm.O4_MINI_2025_04_16: "openai",
Llm.O3_2025_04_16: "openai",
# Anthropic models
Llm.CLAUDE_3_SONNET: "anthropic",
Llm.CLAUDE_3_OPUS: "anthropic",
Llm.CLAUDE_3_HAIKU: "anthropic",
Llm.CLAUDE_3_7_SONNET_2025_02_19: "anthropic",
Llm.CLAUDE_4_SONNET_2025_05_14: "anthropic",
Llm.CLAUDE_4_5_SONNET_2025_09_29: "anthropic",
Llm.CLAUDE_4_OPUS_2025_05_14: "anthropic",
# Gemini models
Llm.GEMINI_2_0_FLASH_EXP: "gemini",
Llm.GEMINI_2_0_FLASH: "gemini",
Llm.GEMINI_2_0_PRO_EXP: "gemini",
Llm.GEMINI_2_5_FLASH_PREVIEW_05_20: "gemini",
}
# Convenience sets for membership checks
OPENAI_MODELS = {m for m, p in MODEL_PROVIDER.items() if p == "openai"}
ANTHROPIC_MODELS = {m for m, p in MODEL_PROVIDER.items() if p == "anthropic"}
GEMINI_MODELS = {m for m, p in MODEL_PROVIDER.items() if p == "gemini"}
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/video_to_app.py | backend/video_to_app.py | # Load environment variables first
from dotenv import load_dotenv
load_dotenv()
import base64
import mimetypes
import time
import subprocess
import os
import asyncio
from datetime import datetime
from prompts.claude_prompts import VIDEO_PROMPT
from utils import pprint_prompt
from config import ANTHROPIC_API_KEY
from video.utils import extract_tag_content, assemble_claude_prompt_video
from llm import Llm
from models import stream_claude_response_native
STACK = "html_tailwind"
VIDEO_DIR = "./video_evals/videos"
SCREENSHOTS_DIR = "./video_evals/screenshots"
OUTPUTS_DIR = "./video_evals/outputs"
async def main():
video_filename = "shortest.mov"
is_followup = False
if not ANTHROPIC_API_KEY:
raise ValueError("ANTHROPIC_API_KEY is not set")
# Get previous HTML
previous_html = ""
if is_followup:
previous_html_file = max(
[
os.path.join(OUTPUTS_DIR, f)
for f in os.listdir(OUTPUTS_DIR)
if f.endswith(".html")
],
key=os.path.getctime,
)
with open(previous_html_file, "r") as file:
previous_html = file.read()
video_file = os.path.join(VIDEO_DIR, video_filename)
mime_type = mimetypes.guess_type(video_file)[0]
with open(video_file, "rb") as file:
video_content = file.read()
video_data_url = (
f"data:{mime_type};base64,{base64.b64encode(video_content).decode('utf-8')}"
)
prompt_messages = await assemble_claude_prompt_video(video_data_url)
# Tell the model to continue
# {"role": "assistant", "content": SECOND_MESSAGE},
# {"role": "user", "content": "continue"},
if is_followup:
prompt_messages += [
{"role": "assistant", "content": previous_html},
{
"role": "user",
"content": "You've done a good job with a first draft. Improve this further based on the original instructions so that the app is fully functional like in the original video.",
},
] # type: ignore
async def process_chunk(content: str):
print(content, end="", flush=True)
response_prefix = "<thinking>"
pprint_prompt(prompt_messages) # type: ignore
start_time = time.time()
completion = await stream_claude_response_native(
system_prompt=VIDEO_PROMPT,
messages=prompt_messages,
api_key=ANTHROPIC_API_KEY,
callback=lambda x: process_chunk(x),
model_name=Llm.CLAUDE_3_OPUS.value,
include_thinking=True,
)
end_time = time.time()
# Prepend the response prefix to the completion
completion = response_prefix + completion
# Extract the outputs
html_content = extract_tag_content("html", completion)
thinking = extract_tag_content("thinking", completion)
print(thinking)
print(f"Operation took {end_time - start_time} seconds")
os.makedirs(OUTPUTS_DIR, exist_ok=True)
# Generate a unique filename based on the current time
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
filename = f"video_test_output_{timestamp}.html"
output_path = os.path.join(OUTPUTS_DIR, filename)
# Write the HTML content to the file
with open(output_path, "w") as file:
file.write(html_content)
print(f"Output file path: {output_path}")
# Show a notification
subprocess.run(["osascript", "-e", 'display notification "Coding Complete"'])
asyncio.run(main())
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/start.py | backend/start.py | import uvicorn
if __name__ == "__main__":
uvicorn.run("main:app", port=7001, reload=True)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/main.py | backend/main.py | # Load environment variables first
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routes import screenshot, generate_code, home, evals
app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
# Configure CORS settings
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Add routes
app.include_router(generate_code.router)
app.include_router(screenshot.router)
app.include_router(home.router)
app.include_router(evals.router)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/utils.py | backend/utils.py | import copy
import json
from typing import List
from openai.types.chat import ChatCompletionMessageParam
def pprint_prompt(prompt_messages: List[ChatCompletionMessageParam]):
print(json.dumps(truncate_data_strings(prompt_messages), indent=4))
def format_prompt_summary(prompt_messages: List[ChatCompletionMessageParam], truncate: bool = True) -> str:
parts: list[str] = []
for message in prompt_messages:
role = message["role"]
content = message["content"]
text = ""
image_count = 0
if isinstance(content, list):
for item in content:
if item["type"] == "text":
text += item["text"] + " "
elif item["type"] == "image_url":
image_count += 1
else:
text = str(content)
text = text.strip()
if truncate and len(text) > 40:
text = text[:40] + "..."
img_part = f" + [{image_count} images]" if image_count else ""
parts.append(f" {role.upper()}: {text}{img_part}")
return "\n".join(parts)
def print_prompt_summary(prompt_messages: List[ChatCompletionMessageParam], truncate: bool = True):
summary = format_prompt_summary(prompt_messages, truncate)
lines = summary.split('\n')
# Find the maximum line length, with a minimum of 20
# If truncating, max is 80, otherwise allow up to 120 for full content
max_allowed = 80 if truncate else 120
max_length = max(len(line) for line in lines) if lines else 20
max_length = max(20, min(max_allowed, max_length))
# Ensure title fits
title = "PROMPT SUMMARY"
max_length = max(max_length, len(title) + 4)
print("┌─" + "─" * max_length + "─┐")
title_padding = (max_length - len(title)) // 2
print(f"│ {' ' * title_padding}{title}{' ' * (max_length - len(title) - title_padding)} │")
print("├─" + "─" * max_length + "─┤")
for line in lines:
if len(line) <= max_length:
print(f"│ {line:<{max_length}} │")
else:
# Wrap long lines
words = line.split()
current_line = ""
for word in words:
if len(current_line + " " + word) <= max_length:
current_line += (" " + word) if current_line else word
else:
if current_line:
print(f"│ {current_line:<{max_length}} │")
current_line = word
if current_line:
print(f"│ {current_line:<{max_length}} │")
print("└─" + "─" * max_length + "─┘")
print()
def truncate_data_strings(data: List[ChatCompletionMessageParam]): # type: ignore
# Deep clone the data to avoid modifying the original object
cloned_data = copy.deepcopy(data)
if isinstance(cloned_data, dict):
for key, value in cloned_data.items(): # type: ignore
# Recursively call the function if the value is a dictionary or a list
if isinstance(value, (dict, list)):
cloned_data[key] = truncate_data_strings(value) # type: ignore
# Truncate the string if it it's long and add ellipsis and length
elif isinstance(value, str):
cloned_data[key] = value[:40] # type: ignore
if len(value) > 40:
cloned_data[key] += "..." + f" ({len(value)} chars)" # type: ignore
elif isinstance(cloned_data, list): # type: ignore
# Process each item in the list
cloned_data = [truncate_data_strings(item) for item in cloned_data] # type: ignore
return cloned_data # type: ignore
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/config.py | backend/config.py | # Useful for debugging purposes when you don't want to waste GPT4-Vision credits
# Setting to True will stream a mock response instead of calling the OpenAI API
# TODO: Should only be set to true when value is 'True', not any abitrary truthy value
import os
NUM_VARIANTS = 4
# LLM-related
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", None)
ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", None)
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", None)
OPENAI_BASE_URL = os.environ.get("OPENAI_BASE_URL", None)
# Image generation (optional)
REPLICATE_API_KEY = os.environ.get("REPLICATE_API_KEY", None)
# Debugging-related
SHOULD_MOCK_AI_RESPONSE = bool(os.environ.get("MOCK", False))
IS_DEBUG_ENABLED = bool(os.environ.get("IS_DEBUG_ENABLED", False))
DEBUG_DIR = os.environ.get("DEBUG_DIR", "")
# Set to True when running in production (on the hosted version)
# Used as a feature flag to enable or disable certain features
IS_PROD = os.environ.get("IS_PROD", False)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/mock_llm.py | backend/mock_llm.py | import asyncio
from typing import Awaitable, Callable
from custom_types import InputMode
from llm import Completion
STREAM_CHUNK_SIZE = 20
async def mock_completion(
process_chunk: Callable[[str, int], Awaitable[None]], input_mode: InputMode
) -> Completion:
code_to_return = (
TALLY_FORM_VIDEO_PROMPT_MOCK
if input_mode == "video"
else NO_IMAGES_NYTIMES_MOCK_CODE
)
for i in range(0, len(code_to_return), STREAM_CHUNK_SIZE):
await process_chunk(code_to_return[i : i + STREAM_CHUNK_SIZE], i)
await asyncio.sleep(0.01)
if input_mode == "video":
# Extract the last <html></html> block from code_to_return
# because we can have multiple passes
start = code_to_return.rfind("<html")
end = code_to_return.rfind("</html>") + len("</html>")
if start != -1 and end != -1:
code_to_return = code_to_return[start:end]
else:
code_to_return = "Error: HTML block not found."
return {"duration": 0.1, "code": code_to_return}
APPLE_MOCK_CODE = """<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Showcase</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Roboto', sans-serif;
}
</style>
</head>
<body class="bg-black text-white">
<nav class="py-6">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex justify-between items-center">
<div class="flex items-center">
<img src="https://placehold.co/24x24" alt="Company Logo" class="mr-8">
<a href="#" class="text-white text-sm font-medium mr-4">Store</a>
<a href="#" class="text-white text-sm font-medium mr-4">Mac</a>
<a href="#" class="text-white text-sm font-medium mr-4">iPad</a>
<a href="#" class="text-white text-sm font-medium mr-4">iPhone</a>
<a href="#" class="text-white text-sm font-medium mr-4">Watch</a>
<a href="#" class="text-white text-sm font-medium mr-4">Vision</a>
<a href="#" class="text-white text-sm font-medium mr-4">AirPods</a>
<a href="#" class="text-white text-sm font-medium mr-4">TV & Home</a>
<a href="#" class="text-white text-sm font-medium mr-4">Entertainment</a>
<a href="#" class="text-white text-sm font-medium mr-4">Accessories</a>
<a href="#" class="text-white text-sm font-medium">Support</a>
</div>
<div class="flex items-center">
<a href="#" class="text-white text-sm font-medium mr-4"><i class="fas fa-search"></i></a>
<a href="#" class="text-white text-sm font-medium"><i class="fas fa-shopping-bag"></i></a>
</div>
</div>
</nav>
<main class="mt-8">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="text-center">
<img src="https://placehold.co/100x100" alt="Brand Logo" class="mx-auto mb-4">
<h1 class="text-5xl font-bold mb-4">WATCH SERIES 9</h1>
<p class="text-2xl font-medium mb-8">Smarter. Brighter. Mightier.</p>
<div class="flex justify-center space-x-4">
<a href="#" class="text-blue-600 text-sm font-medium">Learn more ></a>
<a href="#" class="text-blue-600 text-sm font-medium">Buy ></a>
</div>
</div>
<div class="flex justify-center mt-12">
<img src="https://placehold.co/500x300" alt="Product image of a smartwatch with a pink band and a circular interface displaying various health metrics." class="mr-8">
<img src="https://placehold.co/500x300" alt="Product image of a smartwatch with a blue band and a square interface showing a classic analog clock face." class="ml-8">
</div>
</div>
</main>
</body>
</html>"""
NYTIMES_MOCK_CODE = """
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The New York Times - News</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<style>
body {
font-family: 'Libre Franklin', sans-serif;
}
</style>
</head>
<body class="bg-gray-100">
<div class="container mx-auto px-4">
<header class="border-b border-gray-300 py-4">
<div class="flex justify-between items-center">
<div class="flex items-center space-x-4">
<button class="text-gray-700"><i class="fas fa-bars"></i></button>
<button class="text-gray-700"><i class="fas fa-search"></i></button>
<div class="text-xs uppercase tracking-widest">Tuesday, November 14, 2023<br>Today's Paper</div>
</div>
<div>
<img src="https://placehold.co/200x50?text=The+New+York+Times+Logo" alt="The New York Times Logo" class="h-8">
</div>
<div class="flex items-center space-x-4">
<button class="bg-black text-white px-4 py-1 text-xs uppercase tracking-widest">Give the times</button>
<div class="text-xs">Account</div>
</div>
</div>
<nav class="flex justify-between items-center py-4">
<div class="flex space-x-4">
<a href="#" class="text-xs uppercase tracking-widest text-gray-700">U.S.</a>
<!-- Add other navigation links as needed -->
</div>
<div class="flex space-x-4">
<a href="#" class="text-xs uppercase tracking-widest text-gray-700">Cooking</a>
<!-- Add other navigation links as needed -->
</div>
</nav>
</header>
<main>
<section class="py-6">
<div class="grid grid-cols-3 gap-4">
<div class="col-span-2">
<article class="mb-4">
<h2 class="text-xl font-bold mb-2">Israeli Military Raids Gaza's Largest Hospital</h2>
<p class="text-gray-700 mb-2">Israeli troops have entered the Al-Shifa Hospital complex, where conditions have grown dire and Israel says Hamas fighters are embedded.</p>
<a href="#" class="text-blue-600 text-sm">See more updates <i class="fas fa-external-link-alt"></i></a>
</article>
<!-- Repeat for each news item -->
</div>
<div class="col-span-1">
<article class="mb-4">
<img src="https://placehold.co/300x200?text=News+Image" alt="Flares and plumes of smoke over the northern Gaza skyline on Tuesday." class="mb-2">
<h2 class="text-xl font-bold mb-2">From Elvis to Elopements, the Evolution of the Las Vegas Wedding</h2>
<p class="text-gray-700 mb-2">The glittering city that attracts thousands of couples seeking unconventional nuptials has grown beyond the drive-through wedding.</p>
<a href="#" class="text-blue-600 text-sm">8 MIN READ</a>
</article>
<!-- Repeat for each news item -->
</div>
</div>
</section>
</main>
</div>
</body>
</html>
"""
NO_IMAGES_NYTIMES_MOCK_CODE = """
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The New York Times - News</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Libre+Franklin:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
<style>
body {
font-family: 'Libre Franklin', sans-serif;
}
</style>
</head>
<body class="bg-gray-100">
<div class="container mx-auto px-4">
<header class="border-b border-gray-300 py-4">
<div class="flex justify-between items-center">
<div class="flex items-center space-x-4">
<button class="text-gray-700"><i class="fas fa-bars"></i></button>
<button class="text-gray-700"><i class="fas fa-search"></i></button>
<div class="text-xs uppercase tracking-widest">Tuesday, November 14, 2023<br>Today's Paper</div>
</div>
<div class="flex items-center space-x-4">
<button class="bg-black text-white px-4 py-1 text-xs uppercase tracking-widest">Give the times</button>
<div class="text-xs">Account</div>
</div>
</div>
<nav class="flex justify-between items-center py-4">
<div class="flex space-x-4">
<a href="#" class="text-xs uppercase tracking-widest text-gray-700">U.S.</a>
<!-- Add other navigation links as needed -->
</div>
<div class="flex space-x-4">
<a href="#" class="text-xs uppercase tracking-widest text-gray-700">Cooking</a>
<!-- Add other navigation links as needed -->
</div>
</nav>
</header>
<main>
<section class="py-6">
<div class="grid grid-cols-3 gap-4">
<div class="col-span-2">
<article class="mb-4">
<h2 class="text-xl font-bold mb-2">Israeli Military Raids Gaza's Largest Hospital</h2>
<p class="text-gray-700 mb-2">Israeli troops have entered the Al-Shifa Hospital complex, where conditions have grown dire and Israel says Hamas fighters are embedded.</p>
<a href="#" class="text-blue-600 text-sm">See more updates <i class="fas fa-external-link-alt"></i></a>
</article>
<!-- Repeat for each news item -->
</div>
<div class="col-span-1">
<article class="mb-4">
<h2 class="text-xl font-bold mb-2">From Elvis to Elopements, the Evolution of the Las Vegas Wedding</h2>
<p class="text-gray-700 mb-2">The glittering city that attracts thousands of couples seeking unconventional nuptials has grown beyond the drive-through wedding.</p>
<a href="#" class="text-blue-600 text-sm">8 MIN READ</a>
</article>
<!-- Repeat for each news item -->
</div>
</div>
</section>
</main>
</div>
</body>
</html>
"""
MORTGAGE_CALCULATOR_VIDEO_PROMPT_MOCK = """
<thinking>
The user flow in the video seems to be:
1. The calculator starts with some default values for loan amount, loan term, interest rate, etc.
2. The user toggles the "Include taxes & fees" checkbox which shows an explanation tooltip.
3. The user selects different loan terms from the dropdown, which updates the monthly payment amount.
4. The user enters a custom loan amount.
5. The user selects a different loan term (30-yr fixed FHA).
6. The user enters additional details like home price, down payment, state, credit score, property tax, home insurance, and HOA fees.
7. The calculator updates the total monthly payment breakdown.
To build this:
- Use a container div for the whole calculator
- Have sections for Monthly Payment, Purchase Budget, loan details, additional costs
- Use input fields, dropdowns, and checkboxes for user input
- Update values dynamically using JavaScript when inputs change
- Show/hide explanation tooltip when checkbox is toggled
- Update monthly payment whenever loan amount, interest rate or term is changed
- Allow selecting loan term from a dropdown
- Update total monthly payment breakdown as additional costs are entered
- Style everything to match the screenshots using Tailwind utility classes
</thinking>
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div class="max-w-lg mx-auto bg-white shadow-lg rounded-lg p-6 font-sans">
<div class="text-2xl font-semibold mb-6">Mortgage Calculator</div>
<div class="flex justify-between text-sm uppercase font-semibold text-gray-500 border-b mb-4">
<div class="pb-2 border-b-2 border-blue-500">Monthly payment</div>
<div class="pb-2">Purchase budget</div>
</div>
<div class="flex items-center mb-4">
<input type="checkbox" class="mr-2 taxes-toggle" id="taxesToggle">
<label for="taxesToggle" class="text-sm">Include taxes & fees</label>
<i class="fas fa-info-circle ml-1 text-gray-400 cursor-pointer" id="taxesInfo"></i>
<div class="hidden bg-gray-100 text-xs p-2 ml-2 rounded" id="taxesTooltip">Your total monthly payment is more than just your mortgage. It can include property taxes, homeowners insurance, and HOA fees, among other things.</div>
</div>
<div class="text-3xl font-semibold mb-4">$<span id="monthlyPayment">1,696</span></div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Loan amount</div>
<input type="text" value="240,000" class="w-full border rounded px-2 py-1 text-lg" id="loanAmount">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Loan term</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="loanTerm">
<option>30-yr fixed</option>
<option>30-yr fixed FHA</option>
<option>30-yr fixed VA</option>
<option>30-yr fixed USDA</option>
<option>20-yr fixed</option>
<option>15-yr fixed</option>
<option>10 / 6 ARM</option>
<option>7 / 6 ARM</option>
<option>5 / 6 ARM</option>
<option>3 / 6 ARM</option>
</select>
</div>
<div class="flex justify-between mb-4">
<div>
<div class="text-sm font-semibold mb-2">Interest</div>
<div class="text-lg">7.61 %</div>
</div>
<i class="fas fa-info-circle text-gray-400 cursor-pointer self-center"></i>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Home price</div>
<input type="text" value="300,000" class="w-full border rounded px-2 py-1 text-lg" id="homePrice">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Down payment</div>
<div class="flex">
<input type="text" value="60,000" class="w-full border rounded-l px-2 py-1 text-lg" id="downPayment">
<div class="bg-gray-200 rounded-r px-4 py-1 text-lg flex items-center">20 %</div>
</div>
</div>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">State</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="state">
<option>New York</option>
</select>
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Credit score</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="creditScore">
<option>700 - 719</option>
</select>
</div>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Property tax (yearly)</div>
<input type="text" value="3,750" class="w-full border rounded px-2 py-1 text-lg" id="propertyTax">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Home insurance (yearly)</div>
<input type="text" value="1,050" class="w-full border rounded px-2 py-1 text-lg" id="homeInsurance">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Private mortgage insurance (monthly)</div>
<input type="text" value="0" class="w-full border rounded px-2 py-1 text-lg" id="mortgageInsurance">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Homeowners association (monthly)</div>
<input type="text" value="0" class="w-full border rounded px-2 py-1 text-lg" id="hoaFees">
</div>
</div>
<div class="flex justify-between pt-4">
<div class="text-sm">
<div class="font-semibold">Total monthly payment</div>
<div class="text-3xl font-semibold">$<span id="totalPayment">2,036</span></div>
</div>
<div class="text-right">
<div class="text-sm">Loan</div>
<div class="text-lg">$<span id="loanPayment">1,635</span></div>
<div class="text-sm">Taxes & fees</div>
<div>$<span id="taxesPayment">401</span></div>
</div>
</div>
<div class="text-xs text-gray-500 mt-4">
<div>Disclaimer • Feedback</div>
</div>
</div>
<script>
$(document).ready(function() {
var loanAmount = 240000;
var interestRate = 7.61;
var loanTerm = 30;
var homePrice = 300000;
var downPayment = 60000;
var propertyTax = 3750;
var homeInsurance = 1050;
var mortgageInsurance = 0;
var hoaFees = 0;
function updateCalculations() {
var principal = loanAmount;
var monthlyInterest = interestRate / 100 / 12;
var numPayments = loanTerm * 12;
var monthlyPayment = principal * monthlyInterest / (1 - (Math.pow(1/(1 + monthlyInterest), numPayments)));
var totalPayment = monthlyPayment;
var taxesPayment = (propertyTax + homeInsurance) / 12;
if ($('#taxesToggle').is(':checked')) {
totalPayment += taxesPayment + mortgageInsurance + hoaFees;
}
$('#monthlyPayment').text(Math.round(monthlyPayment).toLocaleString());
$('#loanPayment').text(Math.round(monthlyPayment).toLocaleString());
$('#taxesPayment').text(Math.round(taxesPayment + mortgageInsurance + hoaFees).toLocaleString());
$('#totalPayment').text(Math.round(totalPayment).toLocaleString());
}
$('#taxesInfo').hover(function() {
$('#taxesTooltip').removeClass('hidden');
}, function() {
$('#taxesTooltip').addClass('hidden');
});
$('#loanTerm').change(function() {
loanTerm = parseInt($(this).val().split('-')[0]);
updateCalculations();
});
$('#loanAmount').change(function() {
loanAmount = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#homePrice').change(function() {
homePrice = parseInt($(this).val().replace(/,/g, ''));
loanAmount = homePrice - downPayment;
$('#loanAmount').val(loanAmount.toLocaleString());
updateCalculations();
});
$('#downPayment').change(function() {
downPayment = parseInt($(this).val().replace(/,/g, ''));
loanAmount = homePrice - downPayment;
$('#loanAmount').val(loanAmount.toLocaleString());
updateCalculations();
});
$('#propertyTax').change(function() {
propertyTax = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#homeInsurance').change(function() {
homeInsurance = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#mortgageInsurance').change(function() {
mortgageInsurance = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#hoaFees').change(function() {
hoaFees = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
updateCalculations();
});
</script>
</body>
</html>
<thinking>
More things to consider:
- Add validation to input fields to prevent non-numeric values
- Add a reset button to clear all inputs and reset to default values
</thinking>
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
</head>
<body>
<div class="max-w-lg mx-auto bg-black text-white shadow-lg rounded-lg p-6 font-sans">
<div class="text-2xl font-semibold mb-6">Mortgage Calculator</div>
<div class="flex justify-between text-sm uppercase font-semibold text-gray-500 border-b mb-4">
<div class="pb-2 border-b-2 border-blue-500">Monthly payment</div>
<div class="pb-2">Purchase budget</div>
</div>
<div class="flex items-center mb-4">
<input type="checkbox" class="mr-2 taxes-toggle" id="taxesToggle">
<label for="taxesToggle" class="text-sm">Include taxes & fees</label>
<i class="fas fa-info-circle ml-1 text-gray-400 cursor-pointer" id="taxesInfo"></i>
<div class="hidden bg-gray-100 text-xs p-2 ml-2 rounded" id="taxesTooltip">Your total monthly payment is more than just your mortgage. It can include property taxes, homeowners insurance, and HOA fees, among other things.</div>
</div>
<div class="text-3xl font-semibold mb-4">$<span id="monthlyPayment">1,696</span></div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Loan amount</div>
<input type="text" value="240,000" class="w-full border rounded px-2 py-1 text-lg" id="loanAmount">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Loan term</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="loanTerm">
<option>30-yr fixed</option>
<option>30-yr fixed FHA</option>
<option>30-yr fixed VA</option>
<option>30-yr fixed USDA</option>
<option>20-yr fixed</option>
<option>15-yr fixed</option>
<option>10 / 6 ARM</option>
<option>7 / 6 ARM</option>
<option>5 / 6 ARM</option>
<option>3 / 6 ARM</option>
</select>
</div>
<div class="flex justify-between mb-4">
<div>
<div class="text-sm font-semibold mb-2">Interest</div>
<div class="text-lg">7.61 %</div>
</div>
<i class="fas fa-info-circle text-gray-400 cursor-pointer self-center"></i>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Home price</div>
<input type="text" value="300,000" class="w-full border rounded px-2 py-1 text-lg" id="homePrice">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Down payment</div>
<div class="flex">
<input type="text" value="60,000" class="w-full border rounded-l px-2 py-1 text-lg" id="downPayment">
<div class="bg-gray-200 rounded-r px-4 py-1 text-lg flex items-center">20 %</div>
</div>
</div>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">State</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="state">
<option>New York</option>
</select>
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Credit score</div>
<select class="w-full border rounded px-2 py-1 text-lg" id="creditScore">
<option>700 - 719</option>
</select>
</div>
</div>
<div class="border-t pt-4">
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Property tax (yearly)</div>
<input type="text" value="3,750" class="w-full border rounded px-2 py-1 text-lg" id="propertyTax">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Home insurance (yearly)</div>
<input type="text" value="1,050" class="w-full border rounded px-2 py-1 text-lg" id="homeInsurance">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Private mortgage insurance (monthly)</div>
<input type="text" value="0" class="w-full border rounded px-2 py-1 text-lg" id="mortgageInsurance">
</div>
<div class="mb-4">
<div class="text-sm font-semibold mb-2">Homeowners association (monthly)</div>
<input type="text" value="0" class="w-full border rounded px-2 py-1 text-lg" id="hoaFees">
</div>
</div>
<div class="flex justify-between pt-4">
<div class="text-sm">
<div class="font-semibold">Total monthly payment</div>
<div class="text-3xl font-semibold">$<span id="totalPayment">2,036</span></div>
</div>
<div class="text-right">
<div class="text-sm">Loan</div>
<div class="text-lg">$<span id="loanPayment">1,635</span></div>
<div class="text-sm">Taxes & fees</div>
<div>$<span id="taxesPayment">401</span></div>
</div>
</div>
<div class="text-xs text-gray-500 mt-4">
<div>Disclaimer • Feedback</div>
</div>
</div>
<script>
$(document).ready(function() {
var loanAmount = 240000;
var interestRate = 7.61;
var loanTerm = 30;
var homePrice = 300000;
var downPayment = 60000;
var propertyTax = 3750;
var homeInsurance = 1050;
var mortgageInsurance = 0;
var hoaFees = 0;
function updateCalculations() {
var principal = loanAmount;
var monthlyInterest = interestRate / 100 / 12;
var numPayments = loanTerm * 12;
var monthlyPayment = principal * monthlyInterest / (1 - (Math.pow(1/(1 + monthlyInterest), numPayments)));
var totalPayment = monthlyPayment;
var taxesPayment = (propertyTax + homeInsurance) / 12;
if ($('#taxesToggle').is(':checked')) {
totalPayment += taxesPayment + mortgageInsurance + hoaFees;
}
$('#monthlyPayment').text(Math.round(monthlyPayment).toLocaleString());
$('#loanPayment').text(Math.round(monthlyPayment).toLocaleString());
$('#taxesPayment').text(Math.round(taxesPayment + mortgageInsurance + hoaFees).toLocaleString());
$('#totalPayment').text(Math.round(totalPayment).toLocaleString());
}
$('#taxesInfo').hover(function() {
$('#taxesTooltip').removeClass('hidden');
}, function() {
$('#taxesTooltip').addClass('hidden');
});
$('#loanTerm').change(function() {
loanTerm = parseInt($(this).val().split('-')[0]);
updateCalculations();
});
$('#loanAmount').change(function() {
loanAmount = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#homePrice').change(function() {
homePrice = parseInt($(this).val().replace(/,/g, ''));
loanAmount = homePrice - downPayment;
$('#loanAmount').val(loanAmount.toLocaleString());
updateCalculations();
});
$('#downPayment').change(function() {
downPayment = parseInt($(this).val().replace(/,/g, ''));
loanAmount = homePrice - downPayment;
$('#loanAmount').val(loanAmount.toLocaleString());
updateCalculations();
});
$('#propertyTax').change(function() {
propertyTax = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#homeInsurance').change(function() {
homeInsurance = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#mortgageInsurance').change(function() {
mortgageInsurance = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
$('#hoaFees').change(function() {
hoaFees = parseInt($(this).val().replace(/,/g, ''));
updateCalculations();
});
updateCalculations();
});
</script>
</body>
</html>
"""
GOOGLE_FORM_VIDEO_PROMPT_MOCK = """
<thinking>User flow:
1. User starts on the Google search page and types in "times" in the search bar
2. As the user types, Google provides autocomplete suggestions related to "times"
3. User selects the "times" suggestion from the autocomplete dropdown
4. The search results page for "times" loads, showing various results related to The New York Times newspaper
5. User clicks the "Generate" button under "Get an AI-powered overview for this search?"
6. An AI-generated overview about The New York Times loads on the right side of the search results
Code structure:
- HTML structure with header, search bar, autocomplete dropdown, search button
- Search results area to display search results
- Sidebar area to display the AI-generated overview
- Use Tailwind CSS utility classes for styling
- Use jQuery to handle user interactions:
- Typing in search bar to show/filter autocomplete suggestions
- Selecting autocomplete suggestion to populate search bar
- Clicking search button to display search results
- Clicking "Generate" button to display AI overview
- Hardcode search results and AI overview content for demo purposes
</thinking>
<html>
<head>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"></link>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div class="flex flex-col h-screen">
<div class="flex items-center gap-4 px-5 py-3">
<img class="w-24" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png" alt="Google logo">
<div class="flex-grow relative">
<input type="text" id="search" class="w-full px-4 py-2 text-lg border border-gray-200 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Search Google or type a URL">
<div id="autocomplete" class="absolute w-full bg-white border border-gray-100 rounded-md shadow-lg z-10 hidden">
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">times</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">ts-ebml</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">tiktok ceo</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">two videos</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">Taskrabbit</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">translate</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">Target</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">Taylor Swift</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">Travis Kelce</div>
<div class="px-4 py-2 hover:bg-gray-100 cursor-pointer">Temu</div>
</div>
</div>
<button id="search-btn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md ml-2">
<i class="fas fa-search"></i>
</button>
<img class="w-8 h-8 rounded-full ml-4" src="https://via.placeholder.com/150" alt="Profile picture of the user">
</div>
<div class="flex-grow overflow-y-auto">
<div id="search-results" class="p-8 hidden">
<div class="text-sm text-gray-600 mb-4">Results for New York, NY 10022 - Choose area</div>
<div class="bg-blue-50 p-4 mb-4">
<button id="overview-btn" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md">Get an AI-powered overview for this search?</button>
</div>
<div class="mb-4">
<div class="text-xl text-blue-800 mb-1">
<a href="https://www.nytimes.com">The New York Times</a>
</div>
<div class="text-sm text-gray-800 mb-1">https://www.nytimes.com</div>
<div class="text-sm text-gray-600">
The New York Times - Breaking News, US News, World News ...
</div>
<div class="text-sm text-gray-600">
Live news, investigations, opinion, photos and video by the journalists of The New York Times from more than 150 countries around the world.
</div>
</div>
<div class="mb-4">
<div class="text-sm text-gray-600 mb-1">Opinion | The House Vote to Force TikTok's Sale Is a Mistake - The ...</div>
<div class="text-sm text-gray-600">Why Are Lawmakers Trying to Ban TikTok Instead of Doing What ...</div>
</div>
<div class="mb-4">
<div class="text-sm text-gray-600 mb-1">The Crossword</div>
<div class="text-sm text-gray-600">Play the Daily New York Times Crossword puzzle edited by Will ...</div>
</div>
<div class="mb-4">
<div class="text-sm text-gray-600 mb-1">Today's Paper</div>
<div class="text-sm text-gray-600">Today's Paper · The Front Page · Highlights · Lawyer, Author ...</div>
</div>
<div class="mb-4">
<div class="text-sm text-gray-600 mb-1">Word game Wordle</div>
<div class="text-sm text-gray-600">Get 6 chances to guess a 5-letter word.Get 6 chances to guess a ...</div>
</div>
<div>
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | true |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/fs_logging/core.py | backend/fs_logging/core.py | from datetime import datetime
import json
import os
from openai.types.chat import ChatCompletionMessageParam
def write_logs(prompt_messages: list[ChatCompletionMessageParam], completion: str):
# Get the logs path from environment, default to the current working directory
logs_path = os.environ.get("LOGS_PATH", os.getcwd())
# Create run_logs directory if it doesn't exist within the specified logs path
logs_directory = os.path.join(logs_path, "run_logs")
if not os.path.exists(logs_directory):
os.makedirs(logs_directory)
print("Writing to logs directory:", logs_directory)
# Generate a unique filename using the current timestamp within the logs directory
filename = datetime.now().strftime(f"{logs_directory}/messages_%Y%m%d_%H%M%S.json")
# Write the messages dict into a new file for each run
with open(filename, "w") as f:
f.write(json.dumps({"prompt": prompt_messages, "completion": completion}))
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/fs_logging/__init__.py | backend/fs_logging/__init__.py | python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false | |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/codegen/test_utils.py | backend/codegen/test_utils.py | import unittest
from codegen.utils import extract_html_content
class TestUtils(unittest.TestCase):
def test_extract_html_content_with_html_tags(self):
text = "<html><body><p>Hello, World!</p></body></html>"
expected = "<html><body><p>Hello, World!</p></body></html>"
result = extract_html_content(text)
self.assertEqual(result, expected)
def test_extract_html_content_without_html_tags(self):
text = "No HTML content here."
expected = "No HTML content here."
result = extract_html_content(text)
self.assertEqual(result, expected)
def test_extract_html_content_with_partial_html_tags(self):
text = "<html><body><p>Hello, World!</p></body>"
expected = "<html><body><p>Hello, World!</p></body>"
result = extract_html_content(text)
self.assertEqual(result, expected)
def test_extract_html_content_with_multiple_html_tags(self):
text = "<html><body><p>First</p></body></html> Some text <html><body><p>Second</p></body></html>"
expected = "<html><body><p>First</p></body></html>"
result = extract_html_content(text)
self.assertEqual(result, expected)
## The following are tests based on actual LLM outputs
def test_extract_html_content_some_explanation_before(self):
text = """Got it! You want the song list to be displayed horizontally. I'll update the code to ensure that the song list is displayed in a horizontal layout.
Here's the updated code:
<html lang="en"><head></head><body class="bg-black text-white"></body></html>"""
expected = '<html lang="en"><head></head><body class="bg-black text-white"></body></html>'
result = extract_html_content(text)
self.assertEqual(result, expected)
def test_markdown_tags(self):
text = "```html<head></head>```"
expected = "```html<head></head>```"
result = extract_html_content(text)
self.assertEqual(result, expected)
def test_doctype_text(self):
text = '<!DOCTYPE html><html lang="en"><head></head><body></body></html>'
expected = '<html lang="en"><head></head><body></body></html>'
result = extract_html_content(text)
self.assertEqual(result, expected)
if __name__ == "__main__":
unittest.main()
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/codegen/utils.py | backend/codegen/utils.py | import re
def extract_html_content(text: str):
# Use regex to find content within <html> tags and include the tags themselves
match = re.search(r"(<html.*?>.*?</html>)", text, re.DOTALL)
if match:
return match.group(1)
else:
# Otherwise, we just send the previous HTML over
print(
"[HTML Extraction] No <html> tags found in the generated content: " + text
)
return text
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/codegen/__init__.py | backend/codegen/__init__.py | python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false | |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/evals/runner.py | backend/evals/runner.py | from typing import Any, Coroutine, List, Optional, Tuple
import asyncio
import os
from datetime import datetime
import time
from llm import Llm
from prompts.types import Stack
from .core import generate_code_for_image
from .utils import image_to_data_url
from .config import EVALS_DIR
async def generate_code_and_time(
image_url: str,
stack: Stack,
model: Llm,
original_input_filename: str,
attempt_idx: int,
) -> Tuple[str, int, Optional[str], Optional[float], Optional[Exception]]:
"""
Generates code for an image, measures the time taken, and returns identifiers
along with success/failure status.
Returns a tuple: (original_input_filename, attempt_idx, content, duration, error_object)
content and duration are None if an error occurs during generation.
"""
start_time = time.perf_counter()
try:
content = await generate_code_for_image(
image_url=image_url, stack=stack, model=model
)
end_time = time.perf_counter()
duration = end_time - start_time
return original_input_filename, attempt_idx, content, duration, None
except Exception as e:
print(
f"Error during code generation for {original_input_filename} (attempt {attempt_idx}): {e}"
)
return original_input_filename, attempt_idx, None, None, e
async def run_image_evals(
stack: Optional[Stack] = None,
model: Optional[str] = None,
n: int = 1,
input_files: Optional[List[str]] = None
) -> List[str]:
INPUT_DIR = EVALS_DIR + "/inputs"
OUTPUT_DIR = EVALS_DIR + "/outputs"
# Get all evaluation image files
if input_files and len(input_files) > 0:
# Use the explicitly provided file list
evals = [os.path.basename(f) for f in input_files if f.endswith(".png")]
else:
# Use all PNG files from the input directory
evals = [f for f in os.listdir(INPUT_DIR) if f.endswith(".png")]
if not stack:
raise ValueError("No stack was provided")
if not model:
raise ValueError("No model was provided")
print("User selected stack:", stack)
print("User selected model:", model)
selected_model = Llm(model)
print(f"Running evals for {selected_model.value} model")
if input_files and len(input_files) > 0:
print(f"Running on {len(evals)} selected files")
else:
print(f"Running on all {len(evals)} files in {INPUT_DIR}")
today = datetime.now().strftime("%b_%d_%Y")
output_subfolder = os.path.join(
OUTPUT_DIR, f"{today}_{selected_model.value}_{stack}"
)
os.makedirs(output_subfolder, exist_ok=True)
task_coroutines: List[
Coroutine[
Any,
Any,
Tuple[str, int, Optional[str], Optional[float], Optional[Exception]],
]
] = []
for original_filename in evals:
# Handle both full paths and relative filenames
if os.path.isabs(original_filename):
filepath = original_filename
original_filename = os.path.basename(original_filename)
else:
filepath = os.path.join(INPUT_DIR, original_filename)
data_url = await image_to_data_url(filepath)
for n_idx in range(n):
current_model_for_task = (
selected_model if n_idx == 0 else Llm.GPT_4O_2024_05_13
)
coro = generate_code_and_time(
image_url=data_url,
stack=stack,
model=current_model_for_task,
original_input_filename=original_filename,
attempt_idx=n_idx,
)
task_coroutines.append(coro)
print(f"Processing {len(task_coroutines)} tasks...")
output_files: List[str] = []
timing_data: List[str] = []
failed_tasks_log: List[str] = []
for future in asyncio.as_completed(task_coroutines):
try:
task_orig_fn, task_attempt_idx, generated_content, time_taken, error_obj = (
await future
)
output_html_filename_base = os.path.splitext(task_orig_fn)[0]
final_output_html_filename = (
f"{output_html_filename_base}_{task_attempt_idx}.html"
)
output_html_filepath = os.path.join(
output_subfolder, final_output_html_filename
)
if error_obj is not None:
failed_tasks_log.append(
f"Input: {task_orig_fn}, Attempt: {task_attempt_idx}, OutputFile: {final_output_html_filename}, Error: Generation failed - {str(error_obj)}"
)
elif generated_content is not None and time_taken is not None:
try:
with open(output_html_filepath, "w") as file:
file.write(generated_content)
timing_data.append(
f"{final_output_html_filename}: {time_taken:.2f} seconds"
)
output_files.append(final_output_html_filename)
print(
f"Successfully processed and wrote {final_output_html_filename}"
)
except Exception as e_write:
failed_tasks_log.append(
f"Input: {task_orig_fn}, Attempt: {task_attempt_idx}, OutputFile: {final_output_html_filename}, Error: Writing to file failed - {str(e_write)}"
)
else:
failed_tasks_log.append(
f"Input: {task_orig_fn}, Attempt: {task_attempt_idx}, OutputFile: {final_output_html_filename}, Error: Unknown issue - content or time_taken is None without explicit error."
)
except Exception as e_as_completed:
print(f"A task in as_completed failed unexpectedly: {e_as_completed}")
failed_tasks_log.append(
f"Critical Error: A task processing failed - {str(e_as_completed)}"
)
# Write timing data for successful tasks
if timing_data:
timing_file_path = os.path.join(output_subfolder, "generation_times.txt")
try:
is_new_or_empty_file = (
not os.path.exists(timing_file_path)
or os.path.getsize(timing_file_path) == 0
)
with open(timing_file_path, "a") as file:
if is_new_or_empty_file:
file.write(f"Model: {selected_model.value}\n")
elif timing_data:
file.write("\n")
file.write("\n".join(timing_data))
print(f"Timing data saved to {timing_file_path}")
except Exception as e:
print(f"Error writing timing file {timing_file_path}: {e}")
# Write log for failed tasks
if failed_tasks_log:
failed_log_path = os.path.join(output_subfolder, "failed_tasks.txt")
try:
with open(failed_log_path, "w") as file:
file.write("\n".join(failed_tasks_log))
print(f"Failed tasks log saved to {failed_log_path}")
except Exception as e:
print(f"Error writing failed tasks log {failed_log_path}: {e}")
return output_files
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/evals/core.py | backend/evals/core.py | from config import ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY
from llm import Llm, ANTHROPIC_MODELS, GEMINI_MODELS
from models import (
stream_claude_response,
stream_gemini_response,
stream_openai_response,
)
from prompts import assemble_prompt
from prompts.types import Stack
from openai.types.chat import ChatCompletionMessageParam
async def generate_code_for_image(image_url: str, stack: Stack, model: Llm) -> str:
prompt_messages = assemble_prompt(image_url, stack)
return await generate_code_core(prompt_messages, model)
async def generate_code_core(
prompt_messages: list[ChatCompletionMessageParam], model: Llm
) -> str:
async def process_chunk(_: str):
pass
if model in ANTHROPIC_MODELS:
if not ANTHROPIC_API_KEY:
raise Exception("Anthropic API key not found")
completion = await stream_claude_response(
prompt_messages,
api_key=ANTHROPIC_API_KEY,
callback=lambda x: process_chunk(x),
model_name=model.value,
)
elif model in GEMINI_MODELS:
if not GEMINI_API_KEY:
raise Exception("Gemini API key not found")
completion = await stream_gemini_response(
prompt_messages,
api_key=GEMINI_API_KEY,
callback=lambda x: process_chunk(x),
model_name=model.value,
)
else:
if not OPENAI_API_KEY:
raise Exception("OpenAI API key not found")
completion = await stream_openai_response(
prompt_messages,
api_key=OPENAI_API_KEY,
base_url=None,
callback=lambda x: process_chunk(x),
model_name=model.value,
)
return completion["code"]
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/evals/utils.py | backend/evals/utils.py | import base64
async def image_to_data_url(filepath: str):
with open(filepath, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
return f"data:image/png;base64,{encoded_string}"
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/evals/config.py | backend/evals/config.py | EVALS_DIR = "./evals_data"
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/evals/__init__.py | backend/evals/__init__.py | python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false | |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/test_model_selection.py | backend/tests/test_model_selection.py | import pytest
from unittest.mock import AsyncMock
from routes.generate_code import ModelSelectionStage
from llm import Llm
class TestModelSelectionAllKeys:
"""Test model selection when all API keys are present."""
def setup_method(self):
"""Set up test fixtures."""
mock_throw_error = AsyncMock()
self.model_selector = ModelSelectionStage(mock_throw_error)
@pytest.mark.asyncio
async def test_text_create(self):
"""Text + Create: GPT-4.1, Claude 3.7, Claude 4, GPT-4.1"""
models = await self.model_selector.select_models(
generation_type="create",
input_mode="text",
openai_api_key="key",
anthropic_api_key="key",
gemini_api_key="key",
)
expected = [
Llm.GPT_4_1_2025_04_14,
Llm.CLAUDE_3_7_SONNET_2025_02_19,
Llm.CLAUDE_4_SONNET_2025_05_14,
Llm.GPT_4_1_2025_04_14, # NUM_VARIANTS=4, cycles back
]
assert models == expected
@pytest.mark.asyncio
async def test_text_update(self):
"""Text + Update: GPT-4.1, Claude 3.7, Claude 4, GPT-4.1"""
models = await self.model_selector.select_models(
generation_type="update",
input_mode="text",
openai_api_key="key",
anthropic_api_key="key",
gemini_api_key="key",
)
expected = [
Llm.GPT_4_1_2025_04_14,
Llm.CLAUDE_3_7_SONNET_2025_02_19,
Llm.CLAUDE_4_SONNET_2025_05_14,
Llm.GPT_4_1_2025_04_14, # NUM_VARIANTS=4, cycles back
]
assert models == expected
@pytest.mark.asyncio
async def test_image_create(self):
"""Image + Create: GPT-4.1, Claude 3.7, Gemini 2.0, GPT-4.1"""
models = await self.model_selector.select_models(
generation_type="create",
input_mode="image",
openai_api_key="key",
anthropic_api_key="key",
gemini_api_key="key",
)
expected = [
Llm.GPT_4_1_2025_04_14,
Llm.CLAUDE_3_7_SONNET_2025_02_19,
Llm.GEMINI_2_0_FLASH,
Llm.GPT_4_1_2025_04_14, # NUM_VARIANTS=4, cycles back
]
assert models == expected
@pytest.mark.asyncio
async def test_image_update(self):
"""Image + Update: GPT-4.1, Claude 3.7, Claude 3.7, GPT-4.1 (no Gemini)"""
models = await self.model_selector.select_models(
generation_type="update",
input_mode="image",
openai_api_key="key",
anthropic_api_key="key",
gemini_api_key="key",
)
expected = [
Llm.GPT_4_1_2025_04_14,
Llm.CLAUDE_3_7_SONNET_2025_02_19,
Llm.CLAUDE_3_7_SONNET_2025_02_19, # Gemini doesn't support update, falls back to Claude
Llm.GPT_4_1_2025_04_14, # NUM_VARIANTS=4, cycles back
]
assert models == expected
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/test_prompt_summary.py | backend/tests/test_prompt_summary.py | import io
import sys
from utils import format_prompt_summary, print_prompt_summary
def test_format_prompt_summary():
messages = [
{"role": "system", "content": "lorem ipsum dolor sit amet"},
{
"role": "user",
"content": [
{"type": "text", "text": "hello world"},
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,AAA"},
},
{
"type": "image_url",
"image_url": {"url": "data:image/png;base64,BBB"},
},
],
},
]
summary = format_prompt_summary(messages)
assert "SYSTEM: lorem ipsum" in summary
assert "[2 images]" in summary
def test_print_prompt_summary():
messages = [
{"role": "system", "content": "short message"},
{"role": "user", "content": "hello"},
]
# Capture stdout
captured_output = io.StringIO()
sys.stdout = captured_output
print_prompt_summary(messages)
# Reset stdout
sys.stdout = sys.__stdout__
output = captured_output.getvalue()
# Check that output contains box characters and content
assert "┌─" in output
assert "└─" in output
assert "PROMPT SUMMARY" in output
assert "SYSTEM: short message" in output
assert "USER: hello" in output
def test_print_prompt_summary_long_content():
messages = [
{"role": "system", "content": "This is a very long system message that should be wrapped properly within the box boundaries"},
{"role": "user", "content": "short"},
]
# Capture stdout
captured_output = io.StringIO()
sys.stdout = captured_output
print_prompt_summary(messages)
# Reset stdout
sys.stdout = sys.__stdout__
output = captured_output.getvalue()
lines = output.strip().split('\n')
# Check that all lines have consistent box formatting
for line in lines:
if line.startswith('│') and line.endswith('│'):
# All content lines should have same length
assert len(line) == len(lines[0]) if lines[0].startswith('┌') else True
# Check content is present
assert "PROMPT SUMMARY" in output
assert "SYSTEM:" in output
assert "USER: short" in output
def test_format_prompt_summary_no_truncate():
messages = [
{"role": "system", "content": "This is a very long message that would normally be truncated at 40 characters but should be shown in full"},
]
# Test with truncation (default)
summary_truncated = format_prompt_summary(messages)
assert "..." in summary_truncated
assert len(summary_truncated.split(": ", 1)[1]) <= 50 # Role + truncated content
# Test without truncation
summary_full = format_prompt_summary(messages, truncate=False)
assert "..." not in summary_full
assert "shown in full" in summary_full
def test_print_prompt_summary_no_truncate():
messages = [
{"role": "system", "content": "This is a very long message that would normally be truncated but should be shown in full when truncate=False"},
]
# Capture stdout
captured_output = io.StringIO()
sys.stdout = captured_output
print_prompt_summary(messages, truncate=False)
# Reset stdout
sys.stdout = sys.__stdout__
output = captured_output.getvalue()
# Check that full content is shown
assert "shown in full when truncate=False" in output
assert "..." not in output
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/test_prompts.py | backend/tests/test_prompts.py | import pytest
from unittest.mock import patch, MagicMock
import sys
from typing import Any, Dict, List, TypedDict
from openai.types.chat import ChatCompletionMessageParam
# Mock moviepy before importing prompts
sys.modules["moviepy"] = MagicMock()
sys.modules["moviepy.editor"] = MagicMock()
from prompts import create_prompt
from prompts.types import Stack
# Type definitions for test structures
class ExpectedResult(TypedDict):
messages: List[ChatCompletionMessageParam]
image_cache: Dict[str, str]
def assert_structure_match(actual: object, expected: object, path: str = "") -> None:
"""
Compare actual and expected structures with special markers:
- <ANY>: Matches any value
- <CONTAINS:text>: Checks if the actual value contains 'text'
Args:
actual: The actual value to check
expected: The expected value or pattern
path: Current path in the structure (for error messages)
"""
if (
isinstance(expected, str)
and expected.startswith("<")
and expected.endswith(">")
):
# Handle special markers
if expected == "<ANY>":
# Match any value
return
elif expected.startswith("<CONTAINS:") and expected.endswith(">"):
# Extract the text to search for
search_text = expected[10:-1] # Remove "<CONTAINS:" and ">"
assert isinstance(
actual, str
), f"At {path}: expected string, got {type(actual).__name__}"
assert (
search_text in actual
), f"At {path}: '{search_text}' not found in '{actual}'"
return
# Handle different types
if isinstance(expected, dict):
assert isinstance(
actual, dict
), f"At {path}: expected dict, got {type(actual).__name__}"
expected_dict: Dict[str, object] = expected
actual_dict: Dict[str, object] = actual
for key, value in expected_dict.items():
assert key in actual_dict, f"At {path}: key '{key}' not found in actual"
assert_structure_match(actual_dict[key], value, f"{path}.{key}" if path else key)
elif isinstance(expected, list):
assert isinstance(
actual, list
), f"At {path}: expected list, got {type(actual).__name__}"
expected_list: List[object] = expected
actual_list: List[object] = actual
assert len(actual_list) == len(
expected_list
), f"At {path}: list length mismatch (expected {len(expected_list)}, got {len(actual_list)})"
for i, (a, e) in enumerate(zip(actual_list, expected_list)):
assert_structure_match(a, e, f"{path}[{i}]")
else:
# Direct comparison for other types
assert actual == expected, f"At {path}: expected {expected}, got {actual}"
class TestCreatePrompt:
"""Test cases for create_prompt function."""
# Test data constants
TEST_IMAGE_URL: str = "data:image/png;base64,test_image_data"
RESULT_IMAGE_URL: str = "data:image/png;base64,result_image_data"
MOCK_SYSTEM_PROMPT: str = "Mock HTML Tailwind system prompt"
TEST_STACK: Stack = "html_tailwind"
@pytest.mark.asyncio
async def test_image_mode_create_single_image(self) -> None:
"""Test create generation with single image in image mode."""
# Setup test data
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "create",
}
# Mock the system prompts
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
],
"image_cache": {},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_image_mode_update_with_history(self) -> None:
"""Test update generation with conversation history in image mode."""
# Setup test data
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>"}, # Assistant's initial code
{"text": "Make the background blue"}, # User's update request
{"text": "<html>Updated code</html>"}, # Assistant's response
{"text": "Add a header"}, # User's new request
],
}
# Mock the system prompts and image cache function
mock_system_prompts = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), patch(
"prompts.create_alt_url_mapping", return_value={"mock": "cache"}
):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{"role": "user", "content": "Make the background blue"},
{"role": "assistant", "content": "<html>Updated code</html>"},
{"role": "user", "content": "Add a header"},
],
"image_cache": {"mock": "cache"},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_text_mode_create_generation(self) -> None:
"""Test create generation from text description in text mode."""
# Setup test data
text_description: str = "a modern landing page with hero section"
params: Dict[str, Any] = {
"prompt": {
"text": text_description,
"images": []
},
"generationType": "create"
}
# Mock the text system prompts
mock_text_system_prompts: Dict[str, str] = {
self.TEST_STACK: "Mock Text System Prompt"
}
with patch('prompts.TEXT_SYSTEM_PROMPTS', mock_text_system_prompts):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="text",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{
"role": "system",
"content": "Mock Text System Prompt"
},
{
"role": "user",
"content": f"Generate UI for {text_description}"
}
],
"image_cache": {}
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_text_mode_update_with_history(self) -> None:
"""Test update generation with conversation history in text mode."""
# Setup test data
text_description: str = "a dashboard with charts"
params: Dict[str, Any] = {
"prompt": {
"text": text_description,
"images": []
},
"generationType": "update",
"history": [
{"text": "<html>Initial dashboard</html>"}, # Assistant's initial code
{"text": "Add a sidebar"}, # User's update request
{"text": "<html>Dashboard with sidebar</html>"}, # Assistant's response
{"text": "Now add a navigation menu"} # User's new request
]
}
# Mock the text system prompts and image cache function
mock_text_system_prompts: Dict[str, str] = {
self.TEST_STACK: "Mock Text System Prompt"
}
with patch('prompts.TEXT_SYSTEM_PROMPTS', mock_text_system_prompts), \
patch('prompts.create_alt_url_mapping', return_value={"text": "cache"}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="text",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{
"role": "system",
"content": "Mock Text System Prompt"
},
{
"role": "user",
"content": f"Generate UI for {text_description}"
},
{
"role": "assistant",
"content": "<html>Initial dashboard</html>"
},
{
"role": "user",
"content": "Add a sidebar"
},
{
"role": "assistant",
"content": "<html>Dashboard with sidebar</html>"
},
{
"role": "user",
"content": "Now add a navigation menu"
}
],
"image_cache": {"text": "cache"}
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_video_mode_basic_prompt_creation(self) -> None:
"""Test basic video prompt creation in video mode."""
# Setup test data
video_data_url: str = "data:video/mp4;base64,test_video_data"
params: Dict[str, Any] = {
"prompt": {
"text": "",
"images": [video_data_url]
},
"generationType": "create"
}
# Mock the video processing function
mock_video_messages: List[Dict[str, Any]] = [
{
"role": "system",
"content": "Mock Video System Prompt"
},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,frame1",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,frame2",
"detail": "high"
}
},
{
"type": "text",
"text": "Create a functional web app from these video frames"
}
]
}
]
with patch('prompts.assemble_claude_prompt_video', return_value=mock_video_messages):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="video",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{
"role": "system",
"content": "Mock Video System Prompt"
},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,frame1",
"detail": "high"
}
},
{
"type": "image_url",
"image_url": {
"url": "data:image/png;base64,frame2",
"detail": "high"
}
},
{
"type": "text",
"text": "Create a functional web app from these video frames"
}
]
}
],
"image_cache": {}
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_image_mode_update_with_single_image_in_history(self) -> None:
"""Test update with user message containing a single image."""
# Setup test data
reference_image_url: str = "data:image/png;base64,reference_image"
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>", "images": []},
{"text": "Add a button", "images": [reference_image_url]},
{"text": "<html>Code with button</html>", "images": []}
]
}
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": reference_image_url,
"detail": "high",
},
},
{
"type": "text",
"text": "Add a button",
},
],
},
{"role": "assistant", "content": "<html>Code with button</html>"},
],
"image_cache": {"mock": "cache"},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_image_mode_update_with_multiple_images_in_history(self) -> None:
"""Test update with user message containing multiple images."""
# Setup test data
example1_url: str = "data:image/png;base64,example1"
example2_url: str = "data:image/png;base64,example2"
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>", "images": []},
{"text": "Style like these examples", "images": [example1_url, example2_url]},
{"text": "<html>Styled code</html>", "images": []}
]
}
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": example1_url,
"detail": "high",
},
},
{
"type": "image_url",
"image_url": {
"url": example2_url,
"detail": "high",
},
},
{
"type": "text",
"text": "Style like these examples",
},
],
},
{"role": "assistant", "content": "<html>Styled code</html>"},
],
"image_cache": {"mock": "cache"},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_update_with_empty_images_arrays(self) -> None:
"""Test that empty images arrays don't break existing functionality."""
# Setup test data with explicit empty images arrays
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>", "images": []},
{"text": "Make it blue", "images": []}, # Explicit empty array
{"text": "<html>Blue code</html>", "images": []}
]
}
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
patch("prompts.create_alt_url_mapping", return_value={}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure - should be text-only messages
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{"role": "user", "content": "Make it blue"}, # Text-only message
{"role": "assistant", "content": "<html>Blue code</html>"},
],
"image_cache": {},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_imported_code_update_with_images_in_history(self) -> None:
"""Test imported code flow with images in update history."""
# Setup test data
ref_image_url: str = "data:image/png;base64,ref_image"
params: Dict[str, Any] = {
"isImportedFromCode": True,
"generationType": "update",
"history": [
{"text": "<html>Original imported code</html>", "images": []},
{"text": "Update with this reference", "images": [ref_image_url]},
{"text": "<html>Updated code</html>", "images": []}
]
}
# Mock the imported code system prompts
mock_imported_prompts: Dict[str, str] = {
self.TEST_STACK: "Mock Imported Code System Prompt"
}
with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params.get("prompt", {"text": "", "images": []}),
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{
"role": "system",
"content": "Mock Imported Code System Prompt\n Here is the code of the app: <html>Original imported code</html>",
},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": ref_image_url,
"detail": "high",
},
},
{
"type": "text",
"text": "Update with this reference",
},
],
},
{"role": "assistant", "content": "<html>Updated code</html>"},
],
"image_cache": {},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/test_prompts_additional.py | backend/tests/test_prompts_additional.py | import pytest
from unittest.mock import patch, MagicMock
import sys
from typing import Any, Dict, List, TypedDict
from openai.types.chat import ChatCompletionMessageParam
# Mock moviepy before importing prompts
sys.modules["moviepy"] = MagicMock()
sys.modules["moviepy.editor"] = MagicMock()
from prompts import create_prompt
from prompts.types import Stack
# Type definitions for test structures
class ExpectedResult(TypedDict):
messages: List[ChatCompletionMessageParam]
image_cache: Dict[str, str]
def assert_structure_match(actual: object, expected: object, path: str = "") -> None:
"""
Compare actual and expected structures with special markers:
- <ANY>: Matches any value
- <CONTAINS:text>: Checks if the actual value contains 'text'
Args:
actual: The actual value to check
expected: The expected value or pattern
path: Current path in the structure (for error messages)
"""
if (
isinstance(expected, str)
and expected.startswith("<")
and expected.endswith(">")
):
# Handle special markers
if expected == "<ANY>":
# Match any value
return
elif expected.startswith("<CONTAINS:") and expected.endswith(">"):
# Extract the text to search for
search_text = expected[10:-1] # Remove "<CONTAINS:" and ">"
assert isinstance(
actual, str
), f"At {path}: expected string, got {type(actual).__name__}"
assert (
search_text in actual
), f"At {path}: '{search_text}' not found in '{actual}'"
return
# Handle different types
if isinstance(expected, dict):
assert isinstance(
actual, dict
), f"At {path}: expected dict, got {type(actual).__name__}"
expected_dict: Dict[str, object] = expected
actual_dict: Dict[str, object] = actual
for key, value in expected_dict.items():
assert key in actual_dict, f"At {path}: key '{key}' not found in actual"
assert_structure_match(actual_dict[key], value, f"{path}.{key}" if path else key)
elif isinstance(expected, list):
assert isinstance(
actual, list
), f"At {path}: expected list, got {type(actual).__name__}"
expected_list: List[object] = expected
actual_list: List[object] = actual
assert len(actual_list) == len(
expected_list
), f"At {path}: list length mismatch (expected {len(expected_list)}, got {len(actual_list)})"
for i, (a, e) in enumerate(zip(actual_list, expected_list)):
assert_structure_match(a, e, f"{path}[{i}]")
else:
# Direct comparison for other types
assert actual == expected, f"At {path}: expected {expected}, got {actual}"
class TestCreatePromptImageSupport:
"""Test cases for create_prompt function with image support in updates."""
# Test data constants
TEST_IMAGE_URL: str = "data:image/png;base64,test_image_data"
MOCK_SYSTEM_PROMPT: str = "Mock HTML Tailwind system prompt"
TEST_STACK: Stack = "html_tailwind"
@pytest.mark.asyncio
async def test_image_mode_update_with_multiple_images_in_history(self) -> None:
"""Test update with user message containing multiple images."""
# Setup test data
example1_url: str = "data:image/png;base64,example1"
example2_url: str = "data:image/png;base64,example2"
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>", "images": []},
{"text": "Style like these examples", "images": [example1_url, example2_url]},
{"text": "<html>Styled code</html>", "images": []}
]
}
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
patch("prompts.create_alt_url_mapping", return_value={"mock": "cache"}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": example1_url,
"detail": "high",
},
},
{
"type": "image_url",
"image_url": {
"url": example2_url,
"detail": "high",
},
},
{
"type": "text",
"text": "Style like these examples",
},
],
},
{"role": "assistant", "content": "<html>Styled code</html>"},
],
"image_cache": {"mock": "cache"},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_update_with_empty_images_arrays(self) -> None:
"""Test that empty images arrays don't break existing functionality."""
# Setup test data with explicit empty images arrays
params: Dict[str, Any] = {
"prompt": {"text": "", "images": [self.TEST_IMAGE_URL]},
"generationType": "update",
"history": [
{"text": "<html>Initial code</html>", "images": []},
{"text": "Make it blue", "images": []}, # Explicit empty array
{"text": "<html>Blue code</html>", "images": []}
]
}
# Mock the system prompts and image cache function
mock_system_prompts: Dict[str, str] = {self.TEST_STACK: self.MOCK_SYSTEM_PROMPT}
with patch("prompts.SYSTEM_PROMPTS", mock_system_prompts), \
patch("prompts.create_alt_url_mapping", return_value={}):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params["prompt"],
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure - should be text-only messages
expected: ExpectedResult = {
"messages": [
{"role": "system", "content": self.MOCK_SYSTEM_PROMPT},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": self.TEST_IMAGE_URL,
"detail": "high",
},
},
{
"type": "text",
"text": "<CONTAINS:Generate code for a web page that looks exactly like this.>",
},
],
},
{"role": "assistant", "content": "<html>Initial code</html>"},
{"role": "user", "content": "Make it blue"}, # Text-only message
{"role": "assistant", "content": "<html>Blue code</html>"},
],
"image_cache": {},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
@pytest.mark.asyncio
async def test_imported_code_update_with_images_in_history(self) -> None:
"""Test imported code flow with images in update history."""
# Setup test data
ref_image_url: str = "data:image/png;base64,ref_image"
params: Dict[str, Any] = {
"isImportedFromCode": True,
"generationType": "update",
"history": [
{"text": "<html>Original imported code</html>", "images": []},
{"text": "Update with this reference", "images": [ref_image_url]},
{"text": "<html>Updated code</html>", "images": []}
]
}
# Mock the imported code system prompts
mock_imported_prompts: Dict[str, str] = {
self.TEST_STACK: "Mock Imported Code System Prompt"
}
with patch("prompts.IMPORTED_CODE_SYSTEM_PROMPTS", mock_imported_prompts):
# Call the function
messages, image_cache = await create_prompt(
stack=self.TEST_STACK,
input_mode="image",
generation_type=params["generationType"],
prompt=params.get("prompt", {"text": "", "images": []}),
history=params.get("history", []),
is_imported_from_code=params.get("isImportedFromCode", False),
)
# Define expected structure
expected: ExpectedResult = {
"messages": [
{
"role": "system",
"content": "Mock Imported Code System Prompt\n Here is the code of the app: <html>Original imported code</html>",
},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": ref_image_url,
"detail": "high",
},
},
{
"type": "text",
"text": "Update with this reference",
},
],
},
{"role": "assistant", "content": "<html>Updated code</html>"},
],
"image_cache": {},
}
# Assert the structure matches
actual: ExpectedResult = {"messages": messages, "image_cache": image_cache}
assert_structure_match(actual, expected)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/__init__.py | backend/tests/__init__.py | python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false | |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/tests/test_screenshot.py | backend/tests/test_screenshot.py | import pytest
from routes.screenshot import normalize_url
class TestNormalizeUrl:
"""Test cases for URL normalization functionality."""
def test_url_without_protocol(self):
"""Test that URLs without protocol get https:// added."""
assert normalize_url("example.com") == "https://example.com"
assert normalize_url("www.example.com") == "https://www.example.com"
assert normalize_url("subdomain.example.com") == "https://subdomain.example.com"
def test_url_with_http_protocol(self):
"""Test that existing http protocol is preserved."""
assert normalize_url("http://example.com") == "http://example.com"
assert normalize_url("http://www.example.com") == "http://www.example.com"
def test_url_with_https_protocol(self):
"""Test that existing https protocol is preserved."""
assert normalize_url("https://example.com") == "https://example.com"
assert normalize_url("https://www.example.com") == "https://www.example.com"
def test_url_with_path_and_params(self):
"""Test URLs with paths and query parameters."""
assert normalize_url("example.com/path") == "https://example.com/path"
assert normalize_url("example.com/path?param=value") == "https://example.com/path?param=value"
assert normalize_url("example.com:8080/path") == "https://example.com:8080/path"
def test_url_with_whitespace(self):
"""Test that whitespace is stripped."""
assert normalize_url(" example.com ") == "https://example.com"
assert normalize_url("\texample.com\n") == "https://example.com"
def test_invalid_protocols(self):
"""Test that unsupported protocols raise ValueError."""
with pytest.raises(ValueError, match="Unsupported protocol: ftp"):
normalize_url("ftp://example.com")
with pytest.raises(ValueError, match="Unsupported protocol: file"):
normalize_url("file:///path/to/file")
def test_localhost_urls(self):
"""Test localhost URLs."""
assert normalize_url("localhost") == "https://localhost"
assert normalize_url("localhost:3000") == "https://localhost:3000"
assert normalize_url("http://localhost:8080") == "http://localhost:8080"
def test_ip_address_urls(self):
"""Test IP address URLs."""
assert normalize_url("192.168.1.1") == "https://192.168.1.1"
assert normalize_url("192.168.1.1:8080") == "https://192.168.1.1:8080"
assert normalize_url("http://192.168.1.1") == "http://192.168.1.1"
def test_complex_urls(self):
"""Test more complex URL scenarios."""
assert normalize_url("example.com/path/to/page.html#section") == "https://example.com/path/to/page.html#section"
assert normalize_url("user:pass@example.com") == "https://user:pass@example.com"
assert normalize_url("example.com?q=search&lang=en") == "https://example.com?q=search&lang=en"
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
abi/screenshot-to-code | https://github.com/abi/screenshot-to-code/blob/c4893b3a7072f38f05280df5491846f0f0318306/backend/routes/home.py | backend/routes/home.py | from fastapi import APIRouter
from fastapi.responses import HTMLResponse
router = APIRouter()
@router.get("/")
async def get_status():
return HTMLResponse(
content="<h3>Your backend is running correctly. Please open the front-end URL (default is http://localhost:5173) to use screenshot-to-code.</h3>"
)
| python | MIT | c4893b3a7072f38f05280df5491846f0f0318306 | 2026-01-04T14:38:17.893599Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.