Merge branch 'TheAlgorithms:master' into master

This commit is contained in:
Akshay B Shetty 2023-10-06 09:21:38 +05:30 committed by GitHub
commit 93943aa300
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 618 additions and 108 deletions

View File

@ -25,6 +25,7 @@
* [Combination Sum](backtracking/combination_sum.py)
* [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py)
* [Knight Tour](backtracking/knight_tour.py)
* [Match Word Pattern](backtracking/match_word_pattern.py)
* [Minimax](backtracking/minimax.py)
* [N Queens](backtracking/n_queens.py)
* [N Queens Math](backtracking/n_queens_math.py)
@ -50,6 +51,7 @@
* [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py)
* [Is Even](bit_manipulation/is_even.py)
* [Is Power Of Two](bit_manipulation/is_power_of_two.py)
* [Largest Pow Of Two Le Num](bit_manipulation/largest_pow_of_two_le_num.py)
* [Missing Number](bit_manipulation/missing_number.py)
* [Numbers Different Signs](bit_manipulation/numbers_different_signs.py)
* [Reverse Bits](bit_manipulation/reverse_bits.py)
@ -198,6 +200,7 @@
* [Red Black Tree](data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py)
* [Symmetric Tree](data_structures/binary_tree/symmetric_tree.py)
* [Treap](data_structures/binary_tree/treap.py)
* [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
@ -276,6 +279,7 @@
* [Convolve](digital_image_processing/filters/convolve.py)
* [Gabor Filter](digital_image_processing/filters/gabor_filter.py)
* [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py)
* [Laplacian Filter](digital_image_processing/filters/laplacian_filter.py)
* [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py)
* [Median Filter](digital_image_processing/filters/median_filter.py)
* [Sobel Filter](digital_image_processing/filters/sobel_filter.py)
@ -322,6 +326,7 @@
* [Integer Partition](dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py)
* [Knapsack](dynamic_programming/knapsack.py)
* [Largest Divisible Subset](dynamic_programming/largest_divisible_subset.py)
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
* [Longest Common Substring](dynamic_programming/longest_common_substring.py)
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
@ -363,8 +368,10 @@
* [Ind Reactance](electronics/ind_reactance.py)
* [Ohms Law](electronics/ohms_law.py)
* [Real And Reactive Power](electronics/real_and_reactive_power.py)
* [Resistor Color Code](electronics/resistor_color_code.py)
* [Resistor Equivalence](electronics/resistor_equivalence.py)
* [Resonant Frequency](electronics/resonant_frequency.py)
* [Wheatstone Bridge](electronics/wheatstone_bridge.py)
## File Transfer
* [Receive File](file_transfer/receive_file.py)
@ -413,6 +420,7 @@
* [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](graphs/check_cycle.py)
* [Connected Components](graphs/connected_components.py)
* [Deep Clone Graph](graphs/deep_clone_graph.py)
* [Depth First Search](graphs/depth_first_search.py)
* [Depth First Search 2](graphs/depth_first_search_2.py)
* [Dijkstra](graphs/dijkstra.py)
@ -460,6 +468,7 @@
## Greedy Methods
* [Fractional Knapsack](greedy_methods/fractional_knapsack.py)
* [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py)
* [Gas Station](greedy_methods/gas_station.py)
* [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py)
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
@ -542,6 +551,7 @@
* [Average Median](maths/average_median.py)
* [Average Mode](maths/average_mode.py)
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
* [Base Neg2 Conversion](maths/base_neg2_conversion.py)
* [Basic Maths](maths/basic_maths.py)
* [Bell Numbers](maths/bell_numbers.py)
* [Binary Exp Mod](maths/binary_exp_mod.py)
@ -657,7 +667,6 @@
* [P Series](maths/series/p_series.py)
* [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py)
* [Sigmoid](maths/sigmoid.py)
* [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py)
* [Signum](maths/signum.py)
* [Simpson Rule](maths/simpson_rule.py)
* [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py)
@ -716,6 +725,7 @@
* [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py)
* [Rectified Linear Unit](neural_network/activation_functions/rectified_linear_unit.py)
* [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py)
* [Sigmoid Linear Unit](neural_network/activation_functions/sigmoid_linear_unit.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Perceptron](neural_network/perceptron.py)
@ -1155,6 +1165,7 @@
* [Autocomplete Using Trie](strings/autocomplete_using_trie.py)
* [Barcode Validator](strings/barcode_validator.py)
* [Boyer Moore Search](strings/boyer_moore_search.py)
* [Camel Case To Snake Case](strings/camel_case_to_snake_case.py)
* [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](strings/capitalize.py)
* [Check Anagrams](strings/check_anagrams.py)
@ -1180,6 +1191,7 @@
* [Naive String Search](strings/naive_string_search.py)
* [Ngram](strings/ngram.py)
* [Palindrome](strings/palindrome.py)
* [Pig Latin](strings/pig_latin.py)
* [Prefix Function](strings/prefix_function.py)
* [Rabin Karp](strings/rabin_karp.py)
* [Remove Duplicate](strings/remove_duplicate.py)

View File

@ -0,0 +1,61 @@
def match_word_pattern(pattern: str, input_string: str) -> bool:
"""
Determine if a given pattern matches a string using backtracking.
pattern: The pattern to match.
input_string: The string to match against the pattern.
return: True if the pattern matches the string, False otherwise.
>>> match_word_pattern("aba", "GraphTreesGraph")
True
>>> match_word_pattern("xyx", "PythonRubyPython")
True
>>> match_word_pattern("GG", "PythonJavaPython")
False
"""
def backtrack(pattern_index: int, str_index: int) -> bool:
"""
>>> backtrack(0, 0)
True
>>> backtrack(0, 1)
True
>>> backtrack(0, 4)
False
"""
if pattern_index == len(pattern) and str_index == len(input_string):
return True
if pattern_index == len(pattern) or str_index == len(input_string):
return False
char = pattern[pattern_index]
if char in pattern_map:
mapped_str = pattern_map[char]
if input_string.startswith(mapped_str, str_index):
return backtrack(pattern_index + 1, str_index + len(mapped_str))
else:
return False
for end in range(str_index + 1, len(input_string) + 1):
substr = input_string[str_index:end]
if substr in str_map:
continue
pattern_map[char] = substr
str_map[substr] = char
if backtrack(pattern_index + 1, end):
return True
del pattern_map[char]
del str_map[substr]
return False
pattern_map: dict[str, str] = {}
str_map: dict[str, str] = {}
return backtrack(0, 0)
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -0,0 +1,101 @@
"""
Given the root of a binary tree, check whether it is a mirror of itself
(i.e., symmetric around its center).
Leetcode reference: https://leetcode.com/problems/symmetric-tree/
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
"""
A Node has data variable and pointers to Nodes to its left and right.
"""
data: int
left: Node | None = None
right: Node | None = None
def make_symmetric_tree() -> Node:
r"""
Create a symmetric tree for testing.
The tree looks like this:
1
/ \
2 2
/ \ / \
3 4 4 3
"""
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
return root
def make_asymmetric_tree() -> Node:
r"""
Create a asymmetric tree for testing.
The tree looks like this:
1
/ \
2 2
/ \ / \
3 4 3 4
"""
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(3)
root.right.right = Node(4)
return root
def is_symmetric_tree(tree: Node) -> bool:
"""
Test cases for is_symmetric_tree function
>>> is_symmetric_tree(make_symmetric_tree())
True
>>> is_symmetric_tree(make_asymmetric_tree())
False
"""
if tree:
return is_mirror(tree.left, tree.right)
return True # An empty tree is considered symmetric.
def is_mirror(left: Node | None, right: Node | None) -> bool:
"""
>>> tree1 = make_symmetric_tree()
>>> tree1.right.right = Node(3)
>>> is_mirror(tree1.left, tree1.right)
True
>>> tree2 = make_asymmetric_tree()
>>> is_mirror(tree2.left, tree2.right)
False
"""
if left is None and right is None:
# Both sides are empty, which is symmetric.
return True
if left is None or right is None:
# One side is empty while the other is not, which is not symmetric.
return False
if left.data == right.data:
# The values match, so check the subtree
return is_mirror(left.left, right.right) and is_mirror(left.right, right.left)
return False
if __name__ == "__main__":
from doctest import testmod
testmod()

View File

@ -1,22 +1,91 @@
from __future__ import annotations
from collections.abc import Iterable, Iterator
from dataclasses import dataclass
@dataclass
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.append(f"{temp.data}")
temp = temp.next
return "->".join(string_rep)
data: int
next_node: Node | None = None
def make_linked_list(elements_list: list):
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([])
@ -28,43 +97,30 @@ def make_linked_list(elements_list: list):
>>> make_linked_list(['abc'])
abc
>>> make_linked_list([7, 25])
7->25
7 -> 25
"""
if not elements_list:
raise Exception("The Elements List is empty")
current = head = Node(elements_list[0])
for i in range(1, len(elements_list)):
current.next = Node(elements_list[i])
current = current.next
return head
linked_list = LinkedList()
linked_list.extend(elements_list)
return linked_list
def print_reverse(head_node: Node) -> None:
def in_reverse(linked_list: LinkedList) -> str:
"""Prints the elements of the given Linked List in reverse order
>>> print_reverse([])
>>> linked_list = make_linked_list([69, 88, 73])
>>> print_reverse(linked_list)
73
88
69
>>> in_reverse(LinkedList())
''
>>> in_reverse(make_linked_list([69, 88, 73]))
'73 <- 88 <- 69'
"""
if head_node is not None and isinstance(head_node, Node):
print_reverse(head_node.next)
print(head_node.data)
def main():
from doctest import testmod
testmod()
linked_list = make_linked_list([14, 52, 14, 12, 43])
print("Linked List:")
print(linked_list)
print("Elements in Reverse:")
print_reverse(linked_list)
return " <- ".join(str(line) for line in reversed(tuple(linked_list)))
if __name__ == "__main__":
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)}")

View File

@ -1,27 +1,38 @@
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Any
@dataclass
class Node:
def __init__(self, data: Any):
"""
Create and initialize Node class instance.
>>> Node(20)
Node(20)
>>> Node("Hello, world!")
Node(Hello, world!)
>>> Node(None)
Node(None)
>>> Node(True)
Node(True)
"""
self.data = data
self.next = None
"""
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})"
@ -31,10 +42,12 @@ class LinkedList:
"""
Create and initialize LinkedList class instance.
>>> linked_list = LinkedList()
>>> linked_list.head is None
True
"""
self.head = None
def __iter__(self) -> Any:
def __iter__(self) -> Iterator[Any]:
"""
This function is intended for iterators to access
and iterate through data inside linked list.
@ -51,7 +64,7 @@ class LinkedList:
node = self.head
while node:
yield node.data
node = node.next
node = node.next_node
def __len__(self) -> int:
"""
@ -81,9 +94,16 @@ class LinkedList:
>>> linked_list.insert_tail(1)
>>> linked_list.insert_tail(3)
>>> linked_list.__repr__()
'1->3'
'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])
return " -> ".join([str(item) for item in self])
def __getitem__(self, index: int) -> Any:
"""
@ -134,7 +154,7 @@ class LinkedList:
raise ValueError("list index out of range.")
current = self.head
for _ in range(index):
current = current.next
current = current.next_node
current.data = data
def insert_tail(self, data: Any) -> None:
@ -146,10 +166,10 @@ class LinkedList:
tail
>>> linked_list.insert_tail("tail_2")
>>> linked_list
tail->tail_2
tail -> tail_2
>>> linked_list.insert_tail("tail_3")
>>> linked_list
tail->tail_2->tail_3
tail -> tail_2 -> tail_3
"""
self.insert_nth(len(self), data)
@ -162,10 +182,10 @@ class LinkedList:
head
>>> linked_list.insert_head("head_2")
>>> linked_list
head_2->head
head_2 -> head
>>> linked_list.insert_head("head_3")
>>> linked_list
head_3->head_2->head
head_3 -> head_2 -> head
"""
self.insert_nth(0, data)
@ -177,13 +197,13 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
>>> linked_list.insert_nth(1, "fourth")
>>> linked_list
first->fourth->second->third
first -> fourth -> second -> third
>>> linked_list.insert_nth(3, "fifth")
>>> linked_list
first->fourth->second->fifth->third
first -> fourth -> second -> fifth -> third
"""
if not 0 <= index <= len(self):
raise IndexError("list index out of range")
@ -191,14 +211,14 @@ class LinkedList:
if self.head is None:
self.head = new_node
elif index == 0:
new_node.next = self.head # link new_node to head
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
new_node.next = temp.next
temp.next = new_node
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
"""
@ -208,7 +228,7 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
"""
print(self)
@ -221,11 +241,11 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
>>> linked_list.delete_head()
'first'
>>> linked_list
second->third
second -> third
>>> linked_list.delete_head()
'second'
>>> linked_list
@ -248,11 +268,11 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
>>> linked_list.delete_tail()
'third'
>>> linked_list
first->second
first -> second
>>> linked_list.delete_tail()
'second'
>>> linked_list
@ -275,11 +295,11 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
>>> linked_list.delete_nth(1) # delete middle
'second'
>>> linked_list
first->third
first -> third
>>> linked_list.delete_nth(5) # this raises error
Traceback (most recent call last):
...
@ -293,13 +313,13 @@ class LinkedList:
raise IndexError("List index out of range.")
delete_node = self.head # default first node
if index == 0:
self.head = self.head.next
self.head = self.head.next_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next
delete_node = temp.next
temp.next = temp.next.next
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:
@ -322,22 +342,22 @@ class LinkedList:
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first->second->third
first -> second -> third
>>> linked_list.reverse()
>>> linked_list
third->second->first
third -> second -> first
"""
prev = None
current = self.head
while current:
# Store the current node's next node.
next_node = current.next
# Make the current node's next point backwards
current.next = prev
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 (to progress iteration)
# 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
@ -366,17 +386,17 @@ def test_singly_linked_list() -> None:
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))
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 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 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
@ -385,7 +405,7 @@ def test_singly_linked_list() -> None:
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))
assert str(linked_list) == " -> ".join(str(i) for i in range(-8, 1))
def test_singly_linked_list_2() -> None:
@ -417,56 +437,57 @@ def test_singly_linked_list_2() -> None:
# 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"
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"
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"
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"
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"
== "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"
== "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!)"
== "None -> None -> Node(10) -> 77.9 -> Hello, world! -> -192.55555 -> 0 -> "
"5555 -> 7 -> dlrow olleH -> Node(77345112) -> 100 -> Node(Hello again, world!)"
)

View File

@ -0,0 +1,81 @@
# @Author : ojas-wani
# @File : laplacian_filter.py
# @Date : 10/04/2023
import numpy as np
from cv2 import (
BORDER_DEFAULT,
COLOR_BGR2GRAY,
CV_64F,
cvtColor,
filter2D,
imread,
imshow,
waitKey,
)
from digital_image_processing.filters.gaussian_filter import gaussian_filter
def my_laplacian(src: np.ndarray, ksize: int) -> np.ndarray:
"""
:param src: the source image, which should be a grayscale or color image.
:param ksize: the size of the kernel used to compute the Laplacian filter,
which can be 1, 3, 5, or 7.
>>> my_laplacian(src=np.array([]), ksize=0)
Traceback (most recent call last):
...
ValueError: ksize must be in (1, 3, 5, 7)
"""
kernels = {
1: np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]),
3: np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]),
5: np.array(
[
[0, 0, -1, 0, 0],
[0, -1, -2, -1, 0],
[-1, -2, 16, -2, -1],
[0, -1, -2, -1, 0],
[0, 0, -1, 0, 0],
]
),
7: np.array(
[
[0, 0, 0, -1, 0, 0, 0],
[0, 0, -2, -3, -2, 0, 0],
[0, -2, -7, -10, -7, -2, 0],
[-1, -3, -10, 68, -10, -3, -1],
[0, -2, -7, -10, -7, -2, 0],
[0, 0, -2, -3, -2, 0, 0],
[0, 0, 0, -1, 0, 0, 0],
]
),
}
if ksize not in kernels:
msg = f"ksize must be in {tuple(kernels)}"
raise ValueError(msg)
# Apply the Laplacian kernel using convolution
return filter2D(
src, CV_64F, kernels[ksize], 0, borderType=BORDER_DEFAULT, anchor=(0, 0)
)
if __name__ == "__main__":
# read original image
img = imread(r"../image_data/lena.jpg")
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# Applying gaussian filter
blur_image = gaussian_filter(gray, 3, sigma=1)
# Apply multiple Kernel to detect edges
laplacian_image = my_laplacian(ksize=3, src=blur_image)
imshow("Original image", img)
imshow("Detected edges using laplacian filter", laplacian_image)
waitKey(0)

View File

@ -0,0 +1,41 @@
# https://en.wikipedia.org/wiki/Wheatstone_bridge
from __future__ import annotations
def wheatstone_solver(
resistance_1: float, resistance_2: float, resistance_3: float
) -> float:
"""
This function can calculate the unknown resistance in an wheatstone network,
given that the three other resistances in the network are known.
The formula to calculate the same is:
---------------
|Rx=(R2/R1)*R3|
---------------
Usage examples:
>>> wheatstone_solver(resistance_1=2, resistance_2=4, resistance_3=5)
10.0
>>> wheatstone_solver(resistance_1=356, resistance_2=234, resistance_3=976)
641.5280898876405
>>> wheatstone_solver(resistance_1=2, resistance_2=-1, resistance_3=2)
Traceback (most recent call last):
...
ValueError: All resistance values must be positive
>>> wheatstone_solver(resistance_1=0, resistance_2=0, resistance_3=2)
Traceback (most recent call last):
...
ValueError: All resistance values must be positive
"""
if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0:
raise ValueError("All resistance values must be positive")
else:
return float((resistance_2 / resistance_1) * resistance_3)
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -0,0 +1,77 @@
"""
LeetCode 133. Clone Graph
https://leetcode.com/problems/clone-graph/
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (int) and a list (List[Node]) of its
neighbors.
"""
from dataclasses import dataclass
@dataclass
class Node:
value: int = 0
neighbors: list["Node"] | None = None
def __post_init__(self) -> None:
"""
>>> Node(3).neighbors
[]
"""
self.neighbors = self.neighbors or []
def __hash__(self) -> int:
"""
>>> hash(Node(3)) != 0
True
"""
return id(self)
def clone_graph(node: Node | None) -> Node | None:
"""
This function returns a clone of a connected undirected graph.
>>> clone_graph(Node(1))
Node(value=1, neighbors=[])
>>> clone_graph(Node(1, [Node(2)]))
Node(value=1, neighbors=[Node(value=2, neighbors=[])])
>>> clone_graph(None) is None
True
"""
if not node:
return None
originals_to_clones = {} # map nodes to clones
stack = [node]
while stack:
original = stack.pop()
if original in originals_to_clones:
continue
originals_to_clones[original] = Node(original.value)
stack.extend(original.neighbors or [])
for original, clone in originals_to_clones.items():
for neighbor in original.neighbors or []:
cloned_neighbor = originals_to_clones[neighbor]
if not clone.neighbors:
clone.neighbors = []
clone.neighbors.append(cloned_neighbor)
return originals_to_clones[node]
if __name__ == "__main__":
import doctest
doctest.testmod()

View File

@ -0,0 +1,60 @@
def camel_to_snake_case(input_str: str) -> str:
"""
Transforms a camelCase (or PascalCase) string to snake_case
>>> camel_to_snake_case("someRandomString")
'some_random_string'
>>> camel_to_snake_case("SomeRandomStr#ng")
'some_random_str_ng'
>>> camel_to_snake_case("123someRandom123String123")
'123_some_random_123_string_123'
>>> camel_to_snake_case("123SomeRandom123String123")
'123_some_random_123_string_123'
>>> camel_to_snake_case(123)
Traceback (most recent call last):
...
ValueError: Expected string as input, found <class 'int'>
"""
# check for invalid input type
if not isinstance(input_str, str):
msg = f"Expected string as input, found {type(input_str)}"
raise ValueError(msg)
snake_str = ""
for index, char in enumerate(input_str):
if char.isupper():
snake_str += "_" + char.lower()
# if char is lowercase but proceeded by a digit:
elif input_str[index - 1].isdigit() and char.islower():
snake_str += "_" + char
# if char is a digit proceeded by a letter:
elif input_str[index - 1].isalpha() and char.isnumeric():
snake_str += "_" + char.lower()
# if char is not alphanumeric:
elif not char.isalnum():
snake_str += "_"
else:
snake_str += char
# remove leading underscore
if snake_str[0] == "_":
snake_str = snake_str[1:]
return snake_str
if __name__ == "__main__":
from doctest import testmod
testmod()