mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 10:28:39 +00:00
Compare commits
5 Commits
7021afda04
...
f66568e981
Author | SHA1 | Date | |
---|---|---|---|
|
f66568e981 | ||
|
efaf526737 | ||
|
cecf1fdd52 | ||
|
490e645ed3 | ||
|
7618a92fee |
@ -74,10 +74,7 @@ def is_for_table(string1: str, string2: str, count: int) -> bool:
|
||||
"""
|
||||
list1 = list(string1)
|
||||
list2 = list(string2)
|
||||
count_n = 0
|
||||
for i in range(len(list1)):
|
||||
if list1[i] != list2[i]:
|
||||
count_n += 1
|
||||
count_n = sum(item1 != item2 for item1, item2 in zip(list1, list2))
|
||||
return count_n == count
|
||||
|
||||
|
||||
@ -92,40 +89,34 @@ def selection(chart: list[list[int]], prime_implicants: list[str]) -> list[str]:
|
||||
temp = []
|
||||
select = [0] * len(chart)
|
||||
for i in range(len(chart[0])):
|
||||
count = 0
|
||||
rem = -1
|
||||
for j in range(len(chart)):
|
||||
if chart[j][i] == 1:
|
||||
count += 1
|
||||
rem = j
|
||||
count = sum(row[i] == 1 for row in chart)
|
||||
if count == 1:
|
||||
rem = max(j for j, row in enumerate(chart) if row[i] == 1)
|
||||
select[rem] = 1
|
||||
for i in range(len(select)):
|
||||
if select[i] == 1:
|
||||
for j in range(len(chart[0])):
|
||||
if chart[i][j] == 1:
|
||||
for k in range(len(chart)):
|
||||
chart[k][j] = 0
|
||||
temp.append(prime_implicants[i])
|
||||
for i, item in enumerate(select):
|
||||
if item != 1:
|
||||
continue
|
||||
for j in range(len(chart[0])):
|
||||
if chart[i][j] != 1:
|
||||
continue
|
||||
for row in chart:
|
||||
row[j] = 0
|
||||
temp.append(prime_implicants[i])
|
||||
while True:
|
||||
max_n = 0
|
||||
rem = -1
|
||||
count_n = 0
|
||||
for i in range(len(chart)):
|
||||
count_n = chart[i].count(1)
|
||||
if count_n > max_n:
|
||||
max_n = count_n
|
||||
rem = i
|
||||
counts = [chart[i].count(1) for i in range(len(chart))]
|
||||
max_n = max(counts)
|
||||
rem = counts.index(max_n)
|
||||
|
||||
if max_n == 0:
|
||||
return temp
|
||||
|
||||
temp.append(prime_implicants[rem])
|
||||
|
||||
for i in range(len(chart[0])):
|
||||
if chart[rem][i] == 1:
|
||||
for j in range(len(chart)):
|
||||
chart[j][i] = 0
|
||||
for j in range(len(chart[0])):
|
||||
if chart[rem][j] != 1:
|
||||
continue
|
||||
for i in range(len(chart)):
|
||||
chart[i][j] = 0
|
||||
|
||||
|
||||
def prime_implicant_chart(
|
||||
|
@ -2,8 +2,7 @@ import os
|
||||
import random
|
||||
import sys
|
||||
|
||||
from . import cryptomath_module as cryptoMath # noqa: N812
|
||||
from . import rabin_miller as rabinMiller # noqa: N812
|
||||
from . import cryptomath_module, rabin_miller
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@ -13,20 +12,26 @@ def main() -> None:
|
||||
|
||||
|
||||
def generate_key(key_size: int) -> tuple[tuple[int, int], tuple[int, int]]:
|
||||
print("Generating prime p...")
|
||||
p = rabinMiller.generate_large_prime(key_size)
|
||||
print("Generating prime q...")
|
||||
q = rabinMiller.generate_large_prime(key_size)
|
||||
"""
|
||||
>>> random.seed(0) # for repeatability
|
||||
>>> public_key, private_key = generate_key(8)
|
||||
>>> public_key
|
||||
(26569, 239)
|
||||
>>> private_key
|
||||
(26569, 2855)
|
||||
"""
|
||||
p = rabin_miller.generate_large_prime(key_size)
|
||||
q = rabin_miller.generate_large_prime(key_size)
|
||||
n = p * q
|
||||
|
||||
print("Generating e that is relatively prime to (p - 1) * (q - 1)...")
|
||||
# Generate e that is relatively prime to (p - 1) * (q - 1)
|
||||
while True:
|
||||
e = random.randrange(2 ** (key_size - 1), 2 ** (key_size))
|
||||
if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1:
|
||||
if cryptomath_module.gcd(e, (p - 1) * (q - 1)) == 1:
|
||||
break
|
||||
|
||||
print("Calculating d that is mod inverse of e...")
|
||||
d = cryptoMath.find_mod_inverse(e, (p - 1) * (q - 1))
|
||||
# Calculate d that is mod inverse of e
|
||||
d = cryptomath_module.find_mod_inverse(e, (p - 1) * (q - 1))
|
||||
|
||||
public_key = (n, e)
|
||||
private_key = (n, d)
|
||||
|
@ -32,13 +32,13 @@ def main() -> None:
|
||||
letter_code = random_chars(32)
|
||||
file_name = paths[index].split(os.sep)[-1].rsplit(".", 1)[0]
|
||||
file_root = f"{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"
|
||||
cv2.imwrite(f"/{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
|
||||
cv2.imwrite(f"{file_root}.jpg", image, [cv2.IMWRITE_JPEG_QUALITY, 85])
|
||||
print(f"Success {index+1}/{len(new_images)} with {file_name}")
|
||||
annos_list = []
|
||||
for anno in new_annos[index]:
|
||||
obj = f"{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"
|
||||
annos_list.append(obj)
|
||||
with open(f"/{file_root}.txt", "w") as outfile:
|
||||
with open(f"{file_root}.txt", "w") as outfile:
|
||||
outfile.write("\n".join(line for line in annos_list))
|
||||
|
||||
|
||||
|
@ -1,5 +1,62 @@
|
||||
"""
|
||||
r"""
|
||||
A binary search Tree
|
||||
|
||||
Example
|
||||
8
|
||||
/ \
|
||||
3 10
|
||||
/ \ \
|
||||
1 6 14
|
||||
/ \ /
|
||||
4 7 13
|
||||
|
||||
>>> t = BinarySearchTree()
|
||||
>>> t.insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
|
||||
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
|
||||
8 3 1 6 4 7 10 14 13
|
||||
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
|
||||
1 4 7 6 3 13 14 10 8
|
||||
>>> t.remove(20)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Value 20 not found
|
||||
>>> BinarySearchTree().search(6)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
IndexError: Warning: Tree is empty! please use another.
|
||||
|
||||
Other example:
|
||||
|
||||
>>> testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)
|
||||
>>> t = BinarySearchTree()
|
||||
>>> for i in testlist:
|
||||
... t.insert(i)
|
||||
|
||||
Prints all the elements of the list in order traversal
|
||||
>>> print(t)
|
||||
{'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})}
|
||||
|
||||
Test existence
|
||||
>>> t.search(6) is not None
|
||||
True
|
||||
>>> t.search(-1) is not None
|
||||
False
|
||||
|
||||
>>> t.search(6).is_right
|
||||
True
|
||||
>>> t.search(1).is_right
|
||||
False
|
||||
|
||||
>>> t.get_max().value
|
||||
14
|
||||
>>> t.get_min().value
|
||||
1
|
||||
>>> t.empty()
|
||||
False
|
||||
>>> for i in testlist:
|
||||
... t.remove(i)
|
||||
>>> t.empty()
|
||||
True
|
||||
"""
|
||||
|
||||
from collections.abc import Iterable
|
||||
@ -20,6 +77,10 @@ class Node:
|
||||
return str(self.value)
|
||||
return pformat({f"{self.value}": (self.left, self.right)}, indent=1)
|
||||
|
||||
@property
|
||||
def is_right(self) -> bool:
|
||||
return self.parent is not None and self is self.parent.right
|
||||
|
||||
|
||||
class BinarySearchTree:
|
||||
def __init__(self, root: Node | None = None):
|
||||
@ -35,18 +96,13 @@ class BinarySearchTree:
|
||||
if new_children is not None: # reset its kids
|
||||
new_children.parent = node.parent
|
||||
if node.parent is not None: # reset its parent
|
||||
if self.is_right(node): # If it is the right children
|
||||
if node.is_right: # If it is the right child
|
||||
node.parent.right = new_children
|
||||
else:
|
||||
node.parent.left = new_children
|
||||
else:
|
||||
self.root = new_children
|
||||
|
||||
def is_right(self, node: Node) -> bool:
|
||||
if node.parent and node.parent.right:
|
||||
return node == node.parent.right
|
||||
return False
|
||||
|
||||
def empty(self) -> bool:
|
||||
return self.root is None
|
||||
|
||||
@ -119,22 +175,26 @@ class BinarySearchTree:
|
||||
return node
|
||||
|
||||
def remove(self, value: int) -> None:
|
||||
node = self.search(value) # Look for the node with that label
|
||||
if node is not None:
|
||||
if node.left is None and node.right is None: # If it has no children
|
||||
self.__reassign_nodes(node, None)
|
||||
elif node.left is None: # Has only right children
|
||||
self.__reassign_nodes(node, node.right)
|
||||
elif node.right is None: # Has only left children
|
||||
self.__reassign_nodes(node, node.left)
|
||||
else:
|
||||
tmp_node = self.get_max(
|
||||
node.left
|
||||
) # Gets the max value of the left branch
|
||||
self.remove(tmp_node.value) # type: ignore
|
||||
node.value = (
|
||||
tmp_node.value # type: ignore
|
||||
) # Assigns the value to the node to delete and keep tree structure
|
||||
# Look for the node with that label
|
||||
node = self.search(value)
|
||||
if node is None:
|
||||
msg = f"Value {value} not found"
|
||||
raise ValueError(msg)
|
||||
|
||||
if node.left is None and node.right is None: # If it has no children
|
||||
self.__reassign_nodes(node, None)
|
||||
elif node.left is None: # Has only right children
|
||||
self.__reassign_nodes(node, node.right)
|
||||
elif node.right is None: # Has only left children
|
||||
self.__reassign_nodes(node, node.left)
|
||||
else:
|
||||
predecessor = self.get_max(
|
||||
node.left
|
||||
) # Gets the max value of the left branch
|
||||
self.remove(predecessor.value) # type: ignore
|
||||
node.value = (
|
||||
predecessor.value # type: ignore
|
||||
) # Assigns the value to the node to delete and keep tree structure
|
||||
|
||||
def preorder_traverse(self, node: Node | None) -> Iterable:
|
||||
if node is not None:
|
||||
@ -177,55 +237,6 @@ def postorder(curr_node: Node | None) -> list[Node]:
|
||||
return node_list
|
||||
|
||||
|
||||
def binary_search_tree() -> None:
|
||||
r"""
|
||||
Example
|
||||
8
|
||||
/ \
|
||||
3 10
|
||||
/ \ \
|
||||
1 6 14
|
||||
/ \ /
|
||||
4 7 13
|
||||
|
||||
>>> t = BinarySearchTree()
|
||||
>>> t.insert(8, 3, 6, 1, 10, 14, 13, 4, 7)
|
||||
>>> print(" ".join(repr(i.value) for i in t.traversal_tree()))
|
||||
8 3 1 6 4 7 10 14 13
|
||||
>>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder)))
|
||||
1 4 7 6 3 13 14 10 8
|
||||
>>> BinarySearchTree().search(6)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
IndexError: Warning: Tree is empty! please use another.
|
||||
"""
|
||||
testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7)
|
||||
t = BinarySearchTree()
|
||||
for i in testlist:
|
||||
t.insert(i)
|
||||
|
||||
# Prints all the elements of the list in order traversal
|
||||
print(t)
|
||||
|
||||
if t.search(6) is not None:
|
||||
print("The value 6 exists")
|
||||
else:
|
||||
print("The value 6 doesn't exist")
|
||||
|
||||
if t.search(-1) is not None:
|
||||
print("The value -1 exists")
|
||||
else:
|
||||
print("The value -1 doesn't exist")
|
||||
|
||||
if not t.empty():
|
||||
print("Max Value: ", t.get_max().value) # type: ignore
|
||||
print("Min Value: ", t.get_min().value) # type: ignore
|
||||
|
||||
for i in testlist:
|
||||
t.remove(i)
|
||||
print(t)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
|
@ -21,6 +21,7 @@ def rgb2gray(rgb: np.array) -> np.array:
|
||||
def gray2binary(gray: np.array) -> np.array:
|
||||
"""
|
||||
Return binary image from gray image
|
||||
|
||||
>>> gray2binary(np.array([[127, 255, 0]]))
|
||||
array([[False, True, False]])
|
||||
>>> gray2binary(np.array([[0]]))
|
||||
|
@ -10,12 +10,12 @@ def get_rotation(
|
||||
) -> np.ndarray:
|
||||
"""
|
||||
Get image rotation
|
||||
:param img: np.array
|
||||
:param img: np.ndarray
|
||||
:param pt1: 3x2 list
|
||||
:param pt2: 3x2 list
|
||||
:param rows: columns image shape
|
||||
:param cols: rows image shape
|
||||
:return: np.array
|
||||
:return: np.ndarray
|
||||
"""
|
||||
matrix = cv2.getAffineTransform(pt1, pt2)
|
||||
return cv2.warpAffine(img, matrix, (rows, cols))
|
||||
|
@ -6,14 +6,32 @@ from __future__ import annotations
|
||||
|
||||
Path = list[tuple[int, int]]
|
||||
|
||||
grid = [
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 1, 0, 0, 0, 0],
|
||||
[1, 0, 1, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 1, 0, 0],
|
||||
# 0's are free path whereas 1's are obstacles
|
||||
TEST_GRIDS = [
|
||||
[
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 1, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 1, 0, 0, 0, 0],
|
||||
[1, 0, 1, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 1, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 0, 1, 1, 0, 0],
|
||||
[0, 0, 0, 0, 1, 0, 1],
|
||||
[0, 0, 0, 1, 1, 0, 0],
|
||||
[0, 1, 0, 0, 1, 0, 0],
|
||||
[1, 0, 0, 1, 1, 0, 1],
|
||||
[0, 0, 0, 0, 0, 0, 0],
|
||||
],
|
||||
[
|
||||
[0, 0, 1, 0, 0],
|
||||
[0, 1, 0, 0, 0],
|
||||
[0, 0, 1, 0, 1],
|
||||
[1, 0, 0, 1, 1],
|
||||
[0, 0, 0, 0, 0],
|
||||
],
|
||||
]
|
||||
|
||||
delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
|
||||
@ -65,10 +83,14 @@ class Node:
|
||||
def __lt__(self, other) -> bool:
|
||||
return self.f_cost < other.f_cost
|
||||
|
||||
def __eq__(self, other) -> bool:
|
||||
return self.pos == other.pos
|
||||
|
||||
|
||||
class GreedyBestFirst:
|
||||
"""
|
||||
>>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1))
|
||||
>>> grid = TEST_GRIDS[2]
|
||||
>>> gbf = GreedyBestFirst(grid, (0, 0), (len(grid) - 1, len(grid[0]) - 1))
|
||||
>>> [x.pos for x in gbf.get_successors(gbf.start)]
|
||||
[(1, 0), (0, 1)]
|
||||
>>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1])
|
||||
@ -78,11 +100,14 @@ class GreedyBestFirst:
|
||||
>>> gbf.retrace_path(gbf.start)
|
||||
[(0, 0)]
|
||||
>>> gbf.search() # doctest: +NORMALIZE_WHITESPACE
|
||||
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1),
|
||||
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
|
||||
[(0, 0), (1, 0), (2, 0), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3),
|
||||
(4, 4)]
|
||||
"""
|
||||
|
||||
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
|
||||
def __init__(
|
||||
self, grid: list[list[int]], start: tuple[int, int], goal: tuple[int, int]
|
||||
):
|
||||
self.grid = grid
|
||||
self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)
|
||||
self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)
|
||||
|
||||
@ -114,14 +139,6 @@ class GreedyBestFirst:
|
||||
|
||||
if child_node not in self.open_nodes:
|
||||
self.open_nodes.append(child_node)
|
||||
else:
|
||||
# retrieve the best current path
|
||||
better_node = self.open_nodes.pop(self.open_nodes.index(child_node))
|
||||
|
||||
if child_node.g_cost < better_node.g_cost:
|
||||
self.open_nodes.append(child_node)
|
||||
else:
|
||||
self.open_nodes.append(better_node)
|
||||
|
||||
if not self.reached:
|
||||
return [self.start.pos]
|
||||
@ -131,28 +148,22 @@ class GreedyBestFirst:
|
||||
"""
|
||||
Returns a list of successors (both in the grid and free spaces)
|
||||
"""
|
||||
successors = []
|
||||
for action in delta:
|
||||
pos_x = parent.pos_x + action[1]
|
||||
pos_y = parent.pos_y + action[0]
|
||||
|
||||
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):
|
||||
continue
|
||||
|
||||
if grid[pos_y][pos_x] != 0:
|
||||
continue
|
||||
|
||||
successors.append(
|
||||
Node(
|
||||
pos_x,
|
||||
pos_y,
|
||||
self.target.pos_y,
|
||||
self.target.pos_x,
|
||||
parent.g_cost + 1,
|
||||
parent,
|
||||
)
|
||||
return [
|
||||
Node(
|
||||
pos_x,
|
||||
pos_y,
|
||||
self.target.pos_x,
|
||||
self.target.pos_y,
|
||||
parent.g_cost + 1,
|
||||
parent,
|
||||
)
|
||||
return successors
|
||||
for action in delta
|
||||
if (
|
||||
0 <= (pos_x := parent.pos_x + action[1]) < len(self.grid[0])
|
||||
and 0 <= (pos_y := parent.pos_y + action[0]) < len(self.grid)
|
||||
and self.grid[pos_y][pos_x] == 0
|
||||
)
|
||||
]
|
||||
|
||||
def retrace_path(self, node: Node | None) -> Path:
|
||||
"""
|
||||
@ -168,18 +179,21 @@ class GreedyBestFirst:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
init = (0, 0)
|
||||
goal = (len(grid) - 1, len(grid[0]) - 1)
|
||||
for elem in grid:
|
||||
print(elem)
|
||||
|
||||
print("------")
|
||||
|
||||
greedy_bf = GreedyBestFirst(init, goal)
|
||||
path = greedy_bf.search()
|
||||
if path:
|
||||
for pos_x, pos_y in path:
|
||||
grid[pos_x][pos_y] = 2
|
||||
for idx, grid in enumerate(TEST_GRIDS):
|
||||
print(f"==grid-{idx + 1}==")
|
||||
|
||||
init = (0, 0)
|
||||
goal = (len(grid) - 1, len(grid[0]) - 1)
|
||||
for elem in grid:
|
||||
print(elem)
|
||||
|
||||
print("------")
|
||||
|
||||
greedy_bf = GreedyBestFirst(grid, init, goal)
|
||||
path = greedy_bf.search()
|
||||
if path:
|
||||
for pos_x, pos_y in path:
|
||||
grid[pos_x][pos_y] = 2
|
||||
|
||||
for elem in grid:
|
||||
print(elem)
|
||||
|
@ -19,7 +19,9 @@ def median(nums: list) -> int | float:
|
||||
Returns:
|
||||
Median.
|
||||
"""
|
||||
sorted_list = sorted(nums)
|
||||
# The sorted function returns list[SupportsRichComparisonT@sorted]
|
||||
# which does not support `+`
|
||||
sorted_list: list[int] = sorted(nums)
|
||||
length = len(sorted_list)
|
||||
mid_index = length >> 1
|
||||
return (
|
||||
|
@ -5,7 +5,7 @@ import numpy as np
|
||||
|
||||
def euler_modified(
|
||||
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
|
||||
) -> np.array:
|
||||
) -> np.ndarray:
|
||||
"""
|
||||
Calculate solution at each step to an ODE using Euler's Modified Method
|
||||
The Euler Method is straightforward to implement, but can't give accurate solutions.
|
||||
|
@ -13,7 +13,7 @@ This script is inspired by a corresponding research paper.
|
||||
import numpy as np
|
||||
|
||||
|
||||
def sigmoid(vector: np.array) -> np.array:
|
||||
def sigmoid(vector: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Mathematical function sigmoid takes a vector x of K real numbers as input and
|
||||
returns 1/ (1 + e^-x).
|
||||
@ -25,7 +25,7 @@ def sigmoid(vector: np.array) -> np.array:
|
||||
return 1 / (1 + np.exp(-vector))
|
||||
|
||||
|
||||
def gaussian_error_linear_unit(vector: np.array) -> np.array:
|
||||
def gaussian_error_linear_unit(vector: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Implements the Gaussian Error Linear Unit (GELU) function
|
||||
|
||||
|
@ -14,7 +14,11 @@ Jaccard similarity is widely used with MinHashing.
|
||||
"""
|
||||
|
||||
|
||||
def jaccard_similarity(set_a, set_b, alternative_union=False):
|
||||
def jaccard_similarity(
|
||||
set_a: set[str] | list[str] | tuple[str],
|
||||
set_b: set[str] | list[str] | tuple[str],
|
||||
alternative_union=False,
|
||||
):
|
||||
"""
|
||||
Finds the jaccard similarity between two sets.
|
||||
Essentially, its intersection over union.
|
||||
@ -37,41 +41,52 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
|
||||
>>> set_b = {'c', 'd', 'e', 'f', 'h', 'i'}
|
||||
>>> jaccard_similarity(set_a, set_b)
|
||||
0.375
|
||||
|
||||
>>> jaccard_similarity(set_a, set_a)
|
||||
1.0
|
||||
|
||||
>>> jaccard_similarity(set_a, set_a, True)
|
||||
0.5
|
||||
|
||||
>>> set_a = ['a', 'b', 'c', 'd', 'e']
|
||||
>>> set_b = ('c', 'd', 'e', 'f', 'h', 'i')
|
||||
>>> jaccard_similarity(set_a, set_b)
|
||||
0.375
|
||||
>>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')
|
||||
>>> set_b = ['a', 'b', 'c', 'd', 'e']
|
||||
>>> jaccard_similarity(set_a, set_b)
|
||||
0.375
|
||||
>>> set_a = ('c', 'd', 'e', 'f', 'h', 'i')
|
||||
>>> set_b = ['a', 'b', 'c', 'd']
|
||||
>>> jaccard_similarity(set_a, set_b, True)
|
||||
0.2
|
||||
>>> set_a = {'a', 'b'}
|
||||
>>> set_b = ['c', 'd']
|
||||
>>> jaccard_similarity(set_a, set_b)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Set a and b must either both be sets or be either a list or a tuple.
|
||||
"""
|
||||
|
||||
if isinstance(set_a, set) and isinstance(set_b, set):
|
||||
intersection = len(set_a.intersection(set_b))
|
||||
intersection_length = len(set_a.intersection(set_b))
|
||||
|
||||
if alternative_union:
|
||||
union = len(set_a) + len(set_b)
|
||||
union_length = len(set_a) + len(set_b)
|
||||
else:
|
||||
union = len(set_a.union(set_b))
|
||||
union_length = len(set_a.union(set_b))
|
||||
|
||||
return intersection / union
|
||||
return intersection_length / union_length
|
||||
|
||||
if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):
|
||||
elif isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):
|
||||
intersection = [element for element in set_a if element in set_b]
|
||||
|
||||
if alternative_union:
|
||||
union = len(set_a) + len(set_b)
|
||||
return len(intersection) / union
|
||||
return len(intersection) / (len(set_a) + len(set_b))
|
||||
else:
|
||||
union = set_a + [element for element in set_b if element not in set_a]
|
||||
# Cast set_a to list because tuples cannot be mutated
|
||||
union = list(set_a) + [element for element in set_b if element not in set_a]
|
||||
return len(intersection) / len(union)
|
||||
|
||||
return len(intersection) / len(union)
|
||||
return None
|
||||
raise ValueError(
|
||||
"Set a and b must either both be sets or be either a list or a tuple."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
@ -1,16 +1,20 @@
|
||||
"""
|
||||
Author: P Shreyas Shetty
|
||||
Implementation of Newton-Raphson method for solving equations of kind
|
||||
f(x) = 0. It is an iterative method where solution is found by the expression
|
||||
x[n+1] = x[n] + f(x[n])/f'(x[n])
|
||||
If no solution exists, then either the solution will not be found when iteration
|
||||
limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception
|
||||
is raised. If iteration limit is reached, try increasing maxiter.
|
||||
"""
|
||||
Author: P Shreyas Shetty
|
||||
Implementation of Newton-Raphson method for solving equations of kind
|
||||
f(x) = 0. It is an iterative method where solution is found by the expression
|
||||
x[n+1] = x[n] + f(x[n])/f'(x[n])
|
||||
If no solution exists, then either the solution will not be found when iteration
|
||||
limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception
|
||||
is raised. If iteration limit is reached, try increasing maxiter.
|
||||
"""
|
||||
|
||||
import math as m
|
||||
from collections.abc import Callable
|
||||
|
||||
DerivativeFunc = Callable[[float], float]
|
||||
|
||||
|
||||
def calc_derivative(f, a, h=0.001):
|
||||
def calc_derivative(f: DerivativeFunc, a: float, h: float = 0.001) -> float:
|
||||
"""
|
||||
Calculates derivative at point a for function f using finite difference
|
||||
method
|
||||
@ -18,7 +22,14 @@ def calc_derivative(f, a, h=0.001):
|
||||
return (f(a + h) - f(a - h)) / (2 * h)
|
||||
|
||||
|
||||
def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False):
|
||||
def newton_raphson(
|
||||
f: DerivativeFunc,
|
||||
x0: float = 0,
|
||||
maxiter: int = 100,
|
||||
step: float = 0.0001,
|
||||
maxerror: float = 1e-6,
|
||||
logsteps: bool = False,
|
||||
) -> tuple[float, float, list[float]]:
|
||||
a = x0 # set the initial guess
|
||||
steps = [a]
|
||||
error = abs(f(a))
|
||||
@ -36,7 +47,7 @@ def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=Fa
|
||||
if logsteps:
|
||||
# If logstep is true, then log intermediate steps
|
||||
return a, error, steps
|
||||
return a, error
|
||||
return a, error, []
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
@ -1,7 +1,7 @@
|
||||
import numpy as np
|
||||
|
||||
|
||||
def qr_householder(a):
|
||||
def qr_householder(a: np.ndarray):
|
||||
"""Return a QR-decomposition of the matrix A using Householder reflection.
|
||||
|
||||
The QR-decomposition decomposes the matrix A of shape (m, n) into an
|
||||
|
@ -11,7 +11,7 @@ https://en.wikipedia.org/wiki/Sigmoid_function
|
||||
import numpy as np
|
||||
|
||||
|
||||
def sigmoid(vector: np.array) -> np.array:
|
||||
def sigmoid(vector: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Implements the sigmoid function
|
||||
|
||||
|
@ -12,12 +12,12 @@ https://en.wikipedia.org/wiki/Activation_function
|
||||
import numpy as np
|
||||
|
||||
|
||||
def tangent_hyperbolic(vector: np.array) -> np.array:
|
||||
def tangent_hyperbolic(vector: np.ndarray) -> np.ndarray:
|
||||
"""
|
||||
Implements the tanh function
|
||||
|
||||
Parameters:
|
||||
vector: np.array
|
||||
vector: np.ndarray
|
||||
|
||||
Returns:
|
||||
tanh (np.array): The input numpy array after applying tanh.
|
||||
|
Loading…
x
Reference in New Issue
Block a user