mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-26 10:58:40 +00:00
Merge branch 'TheAlgorithms:master' into fix-mypy-errs-5
This commit is contained in:
commit
731624d685
@ -15,17 +15,27 @@ repos:
|
||||
- id: auto-walrus
|
||||
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 22.12.0
|
||||
rev: 23.1.0
|
||||
hooks:
|
||||
- id: black
|
||||
|
||||
- repo: https://github.com/PyCQA/isort
|
||||
rev: 5.11.4
|
||||
rev: 5.12.0
|
||||
hooks:
|
||||
- id: isort
|
||||
args:
|
||||
- --profile=black
|
||||
|
||||
- repo: https://github.com/tox-dev/pyproject-fmt
|
||||
rev: "0.6.0"
|
||||
hooks:
|
||||
- id: pyproject-fmt
|
||||
|
||||
- repo: https://github.com/abravalheri/validate-pyproject
|
||||
rev: v0.12.1
|
||||
hooks:
|
||||
- id: validate-pyproject
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v3.3.1
|
||||
hooks:
|
||||
|
@ -543,8 +543,7 @@
|
||||
* [Euler Modified](maths/euler_modified.py)
|
||||
* [Eulers Totient](maths/eulers_totient.py)
|
||||
* [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py)
|
||||
* [Factorial Iterative](maths/factorial_iterative.py)
|
||||
* [Factorial Recursive](maths/factorial_recursive.py)
|
||||
* [Factorial](maths/factorial.py)
|
||||
* [Factors](maths/factors.py)
|
||||
* [Fermat Little Theorem](maths/fermat_little_theorem.py)
|
||||
* [Fibonacci](maths/fibonacci.py)
|
||||
|
@ -59,7 +59,6 @@ def newton_raphson(
|
||||
|
||||
# Let's Execute
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Find root of trigonometric function
|
||||
# Find value of pi
|
||||
print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}")
|
||||
|
@ -107,7 +107,6 @@ def depth_first_search(
|
||||
|
||||
# We iterate each column in the row to find all possible results in each row
|
||||
for col in range(n):
|
||||
|
||||
# We apply that we learned previously. First we check that in the current board
|
||||
# (possible_board) there are not other same value because if there is it means
|
||||
# that there are a collision in vertical. Then we apply the two formulas we
|
||||
|
@ -53,6 +53,7 @@ def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int:
|
||||
|
||||
# ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid----------------
|
||||
|
||||
|
||||
# This function find the inverses of a i.e., a^(-1)
|
||||
def invert_modulo(a: int, n: int) -> int:
|
||||
"""
|
||||
|
@ -230,7 +230,6 @@ def enigma(
|
||||
# encryption/decryption process --------------------------
|
||||
for symbol in text:
|
||||
if symbol in abc:
|
||||
|
||||
# 1st plugboard --------------------------
|
||||
if symbol in plugboard:
|
||||
symbol = plugboard[symbol]
|
||||
|
@ -39,7 +39,6 @@ def prepare_input(dirty: str) -> str:
|
||||
|
||||
|
||||
def generate_table(key: str) -> list[str]:
|
||||
|
||||
# I and J are used interchangeably to allow
|
||||
# us to use a 5x5 table (25 letters)
|
||||
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
|
||||
|
@ -19,7 +19,6 @@ SQUARE = [
|
||||
|
||||
class PolybiusCipher:
|
||||
def __init__(self) -> None:
|
||||
|
||||
self.SQUARE = np.array(SQUARE)
|
||||
|
||||
def letter_to_numbers(self, letter: str) -> np.ndarray:
|
||||
|
@ -130,7 +130,6 @@ class XORCipher:
|
||||
try:
|
||||
with open(file) as fin:
|
||||
with open("encrypt.out", "w+") as fout:
|
||||
|
||||
# actual encrypt-process
|
||||
for line in fin:
|
||||
fout.write(self.encrypt_string(line, key))
|
||||
@ -155,7 +154,6 @@ class XORCipher:
|
||||
try:
|
||||
with open(file) as fin:
|
||||
with open("decrypt.out", "w+") as fout:
|
||||
|
||||
# actual encrypt-process
|
||||
for line in fin:
|
||||
fout.write(self.decrypt_string(line, key))
|
||||
|
@ -89,7 +89,6 @@ class LZ77Compressor:
|
||||
|
||||
# while there are still characters in text to compress
|
||||
while text:
|
||||
|
||||
# find the next encoding phrase
|
||||
# - triplet with offset, length, indicator (the next encoding character)
|
||||
token = self._find_encoding_token(text, search_buffer)
|
||||
|
@ -28,7 +28,6 @@ import tensorflow as tf
|
||||
from tensorflow.keras import layers, models
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Initialising the CNN
|
||||
# (Sequential- Building the model layer by layer)
|
||||
classifier = models.Sequential()
|
||||
|
@ -9,7 +9,6 @@ https://en.wikipedia.org/wiki/Harris_Corner_Detector
|
||||
|
||||
class HarrisCorner:
|
||||
def __init__(self, k: float, window_size: int):
|
||||
|
||||
"""
|
||||
k : is an empirically determined constant in [0.04,0.06]
|
||||
window_size : neighbourhoods considered
|
||||
@ -25,7 +24,6 @@ class HarrisCorner:
|
||||
return str(self.k)
|
||||
|
||||
def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:
|
||||
|
||||
"""
|
||||
Returns the image with corners identified
|
||||
img_path : path of the image
|
||||
@ -68,7 +66,6 @@ class HarrisCorner:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
edge_detect = HarrisCorner(0.04, 3)
|
||||
color_img, _ = edge_detect.detect("path_to_image")
|
||||
cv2.imwrite("detect.png", color_img)
|
||||
|
@ -2,7 +2,6 @@
|
||||
|
||||
|
||||
def decimal_to_binary(num: int) -> str:
|
||||
|
||||
"""
|
||||
Convert an Integer Decimal Number to a Binary Number as str.
|
||||
>>> decimal_to_binary(0)
|
||||
|
@ -86,7 +86,6 @@ def pressure_and_volume_to_temperature(
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
@ -47,7 +47,7 @@ def int_to_roman(number: int) -> str:
|
||||
True
|
||||
"""
|
||||
result = []
|
||||
for (arabic, roman) in ROMAN:
|
||||
for arabic, roman in ROMAN:
|
||||
(factor, number) = divmod(number, arabic)
|
||||
result.append(roman * factor)
|
||||
if number == 0:
|
||||
|
@ -380,7 +380,6 @@ def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
@ -307,7 +307,6 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
@ -105,7 +105,6 @@ def get_nodes_from_left_to_right(
|
||||
if not root:
|
||||
return
|
||||
if level == 1:
|
||||
|
||||
output.append(root.data)
|
||||
elif level > 1:
|
||||
populate_output(root.left, level - 1)
|
||||
|
@ -58,7 +58,6 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return
|
||||
|
||||
|
||||
def make_tree() -> BinaryTreeNode | None:
|
||||
|
||||
root = insert(None, 15)
|
||||
insert(root, 10)
|
||||
insert(root, 25)
|
||||
|
@ -24,7 +24,6 @@ class DoubleHash(HashTable):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def __hash_function_2(self, value, data):
|
||||
|
||||
next_prime_gt = (
|
||||
next_prime(value % self.size_table)
|
||||
if not is_prime(value % self.size_table)
|
||||
|
@ -32,7 +32,6 @@ class HashTable:
|
||||
return key % self.size_table
|
||||
|
||||
def _step_by_step(self, step_ord):
|
||||
|
||||
print(f"step {step_ord}")
|
||||
print(list(range(len(self.values))))
|
||||
print(self.values)
|
||||
@ -53,7 +52,6 @@ class HashTable:
|
||||
new_key = self.hash_function(key + 1)
|
||||
|
||||
while self.values[new_key] is not None and self.values[new_key] != key:
|
||||
|
||||
if self.values.count(None) > 0:
|
||||
new_key = self.hash_function(new_key + 1)
|
||||
else:
|
||||
|
@ -174,7 +174,6 @@ class BinomialHeap:
|
||||
i.left_tree_size == i.parent.left_tree_size
|
||||
and i.left_tree_size != i.parent.parent.left_tree_size
|
||||
):
|
||||
|
||||
# Neighbouring Nodes
|
||||
previous_node = i.left
|
||||
next_node = i.parent.parent
|
||||
@ -233,7 +232,6 @@ class BinomialHeap:
|
||||
and self.bottom_root.left_tree_size
|
||||
== self.bottom_root.parent.left_tree_size
|
||||
):
|
||||
|
||||
# Next node
|
||||
next_node = self.bottom_root.parent.parent
|
||||
|
||||
|
@ -71,7 +71,6 @@ class SkewHeap(Generic[T]):
|
||||
"""
|
||||
|
||||
def __init__(self, data: Iterable[T] | None = ()) -> None:
|
||||
|
||||
"""
|
||||
>>> sh = SkewHeap([3, 1, 3, 7])
|
||||
>>> list(sh)
|
||||
|
@ -80,7 +80,6 @@ class LinkedList:
|
||||
return None
|
||||
|
||||
def set_head(self, node: Node) -> None:
|
||||
|
||||
if self.head is None:
|
||||
self.head = node
|
||||
self.tail = node
|
||||
@ -143,7 +142,6 @@ class LinkedList:
|
||||
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.get_next()
|
||||
|
@ -36,7 +36,6 @@ def evaluate(expression):
|
||||
|
||||
# iterate over the string in reverse order
|
||||
for c in expression.split()[::-1]:
|
||||
|
||||
# push operand to stack
|
||||
if is_operand(c):
|
||||
stack.append(int(c))
|
||||
|
@ -92,7 +92,6 @@ class Stack(Generic[T]):
|
||||
|
||||
# Code execution starts here
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Start with the empty stack
|
||||
stack: Stack[int] = Stack()
|
||||
|
||||
|
@ -9,7 +9,6 @@ on the current day is less than or equal to its price on the given day.
|
||||
|
||||
|
||||
def calculation_span(price, s):
|
||||
|
||||
n = len(price)
|
||||
# Create a stack and push index of fist element to it
|
||||
st = []
|
||||
@ -20,7 +19,6 @@ def calculation_span(price, s):
|
||||
|
||||
# Calculate span values for rest of the elements
|
||||
for i in range(1, n):
|
||||
|
||||
# Pop elements from stack while stack is not
|
||||
# empty and top of stack is smaller than price[i]
|
||||
while len(st) > 0 and price[st[0]] <= price[i]:
|
||||
|
@ -50,7 +50,6 @@ def bilateral_filter(
|
||||
size_x, size_y = img.shape
|
||||
for i in range(kernel_size // 2, size_x - kernel_size // 2):
|
||||
for j in range(kernel_size // 2, size_y - kernel_size // 2):
|
||||
|
||||
img_s = get_slice(img, i, j, kernel_size)
|
||||
img_i = img_s - img_s[kernel_size // 2, kernel_size // 2]
|
||||
img_ig = vec_gaussian(img_i, intensity_variance)
|
||||
|
@ -61,7 +61,6 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Reading the image and converting it to grayscale.
|
||||
image = cv2.imread(
|
||||
"digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE
|
||||
|
@ -13,7 +13,6 @@ from collections import defaultdict
|
||||
|
||||
class AssignmentUsingBitmask:
|
||||
def __init__(self, task_performed, total):
|
||||
|
||||
self.total_tasks = total # total no of tasks (N)
|
||||
|
||||
# DP table will have a dimension of (2^M)*N
|
||||
@ -29,7 +28,6 @@ class AssignmentUsingBitmask:
|
||||
self.final_mask = (1 << len(task_performed)) - 1
|
||||
|
||||
def count_ways_until(self, mask, task_no):
|
||||
|
||||
# if mask == self.finalmask all persons are distributed tasks, return 1
|
||||
if mask == self.final_mask:
|
||||
return 1
|
||||
@ -49,7 +47,6 @@ class AssignmentUsingBitmask:
|
||||
# assign for the remaining tasks.
|
||||
if task_no in self.task:
|
||||
for p in self.task[task_no]:
|
||||
|
||||
# if p is already given a task
|
||||
if mask & (1 << p):
|
||||
continue
|
||||
@ -64,7 +61,6 @@ class AssignmentUsingBitmask:
|
||||
return self.dp[mask][task_no]
|
||||
|
||||
def count_no_of_ways(self, task_performed):
|
||||
|
||||
# Store the list of persons for each task
|
||||
for i in range(len(task_performed)):
|
||||
for j in task_performed[i]:
|
||||
@ -75,7 +71,6 @@ class AssignmentUsingBitmask:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
total_tasks = 5 # total no of tasks (the value of N)
|
||||
|
||||
# the list of tasks that can be done by M persons.
|
||||
|
@ -9,7 +9,6 @@ from __future__ import annotations
|
||||
|
||||
|
||||
def list_of_submasks(mask: int) -> list[int]:
|
||||
|
||||
"""
|
||||
Args:
|
||||
mask : number which shows mask ( always integer > 0, zero does not have any
|
||||
|
@ -8,7 +8,6 @@ COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2
|
||||
def couloumbs_law(
|
||||
force: float, charge1: float, charge2: float, distance: float
|
||||
) -> dict[str, float]:
|
||||
|
||||
"""
|
||||
Apply Coulomb's Law on any three given values. These can be force, charge1,
|
||||
charge2, or distance, and then in a Python dict return name/value pair of
|
||||
|
@ -170,7 +170,6 @@ def ignore_overflow_warnings() -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
z_0 = prepare_grid(window_size, nb_pixels)
|
||||
|
||||
ignore_overflow_warnings() # See file header for explanations
|
||||
|
@ -114,7 +114,6 @@ def get_image(
|
||||
# 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
|
||||
|
@ -10,7 +10,6 @@ EQUATORIAL_RADIUS = 6378137
|
||||
def lamberts_ellipsoidal_distance(
|
||||
lat1: float, lon1: float, lat2: float, lon2: float
|
||||
) -> float:
|
||||
|
||||
"""
|
||||
Calculate the shortest distance along the surface of an ellipsoid between
|
||||
two points on the surface of earth given longitudes and latitudes
|
||||
|
@ -16,7 +16,6 @@ def search(
|
||||
cost: int,
|
||||
heuristic: list[list[int]],
|
||||
) -> tuple[list[list[int]], list[list[int]]]:
|
||||
|
||||
closed = [
|
||||
[0 for col in range(len(grid[0]))] for row in range(len(grid))
|
||||
] # the reference grid
|
||||
|
@ -20,7 +20,6 @@ def check_bipartite(graph):
|
||||
visited[u] = True
|
||||
|
||||
for neighbour in graph[u]:
|
||||
|
||||
if neighbour == u:
|
||||
return False
|
||||
|
||||
|
@ -8,7 +8,6 @@ class Graph:
|
||||
self.graph[v - 1][u - 1] = 1
|
||||
|
||||
def show(self):
|
||||
|
||||
for i in self.graph:
|
||||
for j in i:
|
||||
print(j, end=" ")
|
||||
|
@ -47,7 +47,6 @@ def partition_graph(graph: dict[str, list[str]]) -> set[tuple[str, str]]:
|
||||
graph_copy = {node: graph[node][:] for node in graph}
|
||||
|
||||
while len(graph_copy) > 2:
|
||||
|
||||
# Choose a random edge.
|
||||
u = random.choice(list(graph_copy.keys()))
|
||||
v = random.choice(graph_copy[u])
|
||||
|
@ -4,7 +4,6 @@ class Graph:
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.num_vertices = 0
|
||||
self.num_edges = 0
|
||||
self.adjacency = {}
|
||||
|
@ -33,7 +33,7 @@ class PriorityQueue:
|
||||
temp.append((pri, x))
|
||||
(pri, x) = heapq.heappop(self.elements)
|
||||
temp.append((priority, item))
|
||||
for (pro, xxx) in temp:
|
||||
for pro, xxx in temp:
|
||||
heapq.heappush(self.elements, (pro, xxx))
|
||||
|
||||
def remove_element(self, item):
|
||||
@ -44,7 +44,7 @@ class PriorityQueue:
|
||||
while x != item:
|
||||
temp.append((pro, x))
|
||||
(pro, x) = heapq.heappop(self.elements)
|
||||
for (prito, yyy) in temp:
|
||||
for prito, yyy in temp:
|
||||
heapq.heappush(self.elements, (prito, yyy))
|
||||
|
||||
def top_show(self):
|
||||
|
@ -46,7 +46,6 @@ def knapsack(
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
@ -115,7 +115,6 @@ def conjugate_gradient(
|
||||
iterations = 0
|
||||
|
||||
while error > tol:
|
||||
|
||||
# Save this value so we only calculate the matrix-vector product once.
|
||||
w = np.dot(spd_matrix, p0)
|
||||
|
||||
|
@ -74,7 +74,6 @@ def centroid_pairwise_dist(x, centroids):
|
||||
|
||||
|
||||
def assign_clusters(data, centroids):
|
||||
|
||||
# Compute distances between each data point and the set of centroids:
|
||||
# Fill in the blank (RHS only)
|
||||
distances_from_centroids = centroid_pairwise_dist(data, centroids)
|
||||
@ -100,10 +99,8 @@ def revise_centroids(data, k, cluster_assignment):
|
||||
|
||||
|
||||
def compute_heterogeneity(data, k, centroids, cluster_assignment):
|
||||
|
||||
heterogeneity = 0.0
|
||||
for i in range(k):
|
||||
|
||||
# Select all data points that belong to cluster i. Fill in the blank (RHS only)
|
||||
member_data_points = data[cluster_assignment == i, :]
|
||||
|
||||
|
@ -49,7 +49,6 @@ def main() -> None:
|
||||
|
||||
for _ in range(epochs):
|
||||
for j in range(len(training_samples)):
|
||||
|
||||
# training sample
|
||||
sample = training_samples[j]
|
||||
|
||||
|
@ -82,7 +82,6 @@ class SmoSVM:
|
||||
k = self._k
|
||||
state = None
|
||||
while True:
|
||||
|
||||
# 1: Find alpha1, alpha2
|
||||
try:
|
||||
i1, i2 = self.choose_alpha.send(state)
|
||||
@ -146,7 +145,6 @@ class SmoSVM:
|
||||
|
||||
# Predict test samples
|
||||
def predict(self, test_samples, classify=True):
|
||||
|
||||
if test_samples.shape[1] > self.samples.shape[1]:
|
||||
raise ValueError(
|
||||
"Test samples' feature length does not equal to that of train samples"
|
||||
|
@ -41,7 +41,6 @@ def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
"""
|
||||
>>> main()
|
||||
|
||||
|
@ -62,7 +62,7 @@ def pluperfect_number(n: int) -> bool:
|
||||
digit_histogram[rem] += 1
|
||||
digit_total += 1
|
||||
|
||||
for (cnt, i) in zip(digit_histogram, range(len(digit_histogram))):
|
||||
for cnt, i in zip(digit_histogram, range(len(digit_histogram))):
|
||||
total += cnt * i**digit_total
|
||||
|
||||
return n == total
|
||||
|
@ -5,7 +5,6 @@
|
||||
|
||||
|
||||
def binary_exponentiation(a, n):
|
||||
|
||||
if n == 0:
|
||||
return 1
|
||||
|
||||
|
@ -39,7 +39,6 @@ def combinations(n: int, k: int) -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
print(
|
||||
"The number of five-card hands possible from a standard",
|
||||
f"fifty-two card deck is: {combinations(52, 5)}\n",
|
||||
|
@ -5,7 +5,6 @@ https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-poi
|
||||
|
||||
|
||||
def decimal_isolate(number: float, digit_amount: int) -> float:
|
||||
|
||||
"""
|
||||
Isolates the decimal part of a number.
|
||||
If digitAmount > 0 round to that decimal place, else print the entire decimal.
|
||||
|
@ -34,6 +34,30 @@ def factorial(number: int) -> int:
|
||||
return value
|
||||
|
||||
|
||||
def factorial_recursive(n: int) -> int:
|
||||
"""
|
||||
Calculate the factorial of a positive integer
|
||||
https://en.wikipedia.org/wiki/Factorial
|
||||
|
||||
>>> import math
|
||||
>>> all(factorial(i) == math.factorial(i) for i in range(20))
|
||||
True
|
||||
>>> factorial(0.1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: factorial() only accepts integral values
|
||||
>>> factorial(-1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: factorial() not defined for negative values
|
||||
"""
|
||||
if not isinstance(n, int):
|
||||
raise ValueError("factorial() only accepts integral values")
|
||||
if n < 0:
|
||||
raise ValueError("factorial() not defined for negative values")
|
||||
return 1 if n == 0 or n == 1 else n * factorial(n - 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
@ -1,28 +0,0 @@
|
||||
def factorial(n: int) -> int:
|
||||
"""
|
||||
Calculate the factorial of a positive integer
|
||||
https://en.wikipedia.org/wiki/Factorial
|
||||
|
||||
>>> import math
|
||||
>>> all(factorial(i) == math.factorial(i) for i in range(20))
|
||||
True
|
||||
>>> factorial(0.1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: factorial() only accepts integral values
|
||||
>>> factorial(-1)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: factorial() not defined for negative values
|
||||
"""
|
||||
if not isinstance(n, int):
|
||||
raise ValueError("factorial() only accepts integral values")
|
||||
if n < 0:
|
||||
raise ValueError("factorial() not defined for negative values")
|
||||
return 1 if n == 0 or n == 1 else n * factorial(n - 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
@ -6,7 +6,6 @@
|
||||
|
||||
|
||||
def binary_exponentiation(a, n, mod):
|
||||
|
||||
if n == 0:
|
||||
return 1
|
||||
|
||||
|
@ -62,7 +62,6 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
|
||||
|
||||
# Traverse through all denomination
|
||||
for denomination in reversed(denominations):
|
||||
|
||||
# Find denominations
|
||||
while int(total_value) >= int(denomination):
|
||||
total_value -= int(denomination)
|
||||
@ -73,7 +72,6 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
|
||||
|
||||
# Driver Code
|
||||
if __name__ == "__main__":
|
||||
|
||||
denominations = []
|
||||
value = "0"
|
||||
|
||||
|
@ -35,7 +35,6 @@ xn = b
|
||||
|
||||
|
||||
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
|
||||
|
||||
"""
|
||||
Args:
|
||||
function : the function which's integration is desired
|
||||
|
@ -51,7 +51,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
|
||||
"""
|
||||
|
||||
if isinstance(set_a, set) and isinstance(set_b, set):
|
||||
|
||||
intersection = len(set_a.intersection(set_b))
|
||||
|
||||
if alternative_union:
|
||||
@ -62,7 +61,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
|
||||
return intersection / union
|
||||
|
||||
if 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:
|
||||
|
@ -67,7 +67,6 @@ def benchmark():
|
||||
|
||||
|
||||
class TestLeastCommonMultiple(unittest.TestCase):
|
||||
|
||||
test_inputs = [
|
||||
(10, 20),
|
||||
(13, 15),
|
||||
|
@ -10,7 +10,6 @@ def line_length(
|
||||
x_end: int | float,
|
||||
steps: int = 100,
|
||||
) -> float:
|
||||
|
||||
"""
|
||||
Approximates the arc length of a line segment by treating the curve as a
|
||||
sequence of linear lines and summing their lengths
|
||||
@ -41,7 +40,6 @@ def line_length(
|
||||
length = 0.0
|
||||
|
||||
for _ in range(steps):
|
||||
|
||||
# Approximates curve as a sequence of linear lines and sums their length
|
||||
x2 = (x_end - x_start) / steps + x1
|
||||
fx2 = fnc(x2)
|
||||
|
@ -18,6 +18,7 @@ def pi_estimator(iterations: int):
|
||||
5. Multiply this value by 4 to get your estimate of pi.
|
||||
6. Print the estimated and numpy value of pi
|
||||
"""
|
||||
|
||||
# A local function to see if a dot lands in the circle.
|
||||
def is_in_circle(x: float, y: float) -> bool:
|
||||
distance_from_centre = sqrt((x**2) + (y**2))
|
||||
|
@ -19,7 +19,6 @@ def calc_derivative(f, a, h=0.001):
|
||||
|
||||
|
||||
def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False):
|
||||
|
||||
a = x0 # set the initial guess
|
||||
steps = [a]
|
||||
error = abs(f(a))
|
||||
|
@ -12,7 +12,6 @@ def trapezoidal_area(
|
||||
x_end: int | float,
|
||||
steps: int = 100,
|
||||
) -> float:
|
||||
|
||||
"""
|
||||
Treats curve as a collection of linear lines and sums the area of the
|
||||
trapezium shape they form
|
||||
@ -40,7 +39,6 @@ def trapezoidal_area(
|
||||
area = 0.0
|
||||
|
||||
for _ in range(steps):
|
||||
|
||||
# Approximates small segments of curve as linear and solve
|
||||
# for trapezoidal area
|
||||
x2 = (x_end - x_start) / steps + x1
|
||||
|
@ -59,7 +59,6 @@ def is_prime(number: int) -> bool:
|
||||
status = False
|
||||
|
||||
for divisor in range(2, int(round(sqrt(number))) + 1):
|
||||
|
||||
# if 'number' divisible by 'divisor' then sets 'status'
|
||||
# of false and break up the loop.
|
||||
if number % divisor == 0:
|
||||
@ -95,9 +94,7 @@ def sieve_er(n):
|
||||
|
||||
# actual sieve of erathostenes
|
||||
for i in range(len(begin_list)):
|
||||
|
||||
for j in range(i + 1, len(begin_list)):
|
||||
|
||||
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
|
||||
begin_list[j] = 0
|
||||
|
||||
@ -128,9 +125,7 @@ def get_prime_numbers(n):
|
||||
# iterates over all numbers between 2 up to N+1
|
||||
# if a number is prime then appends to list 'ans'
|
||||
for number in range(2, n + 1):
|
||||
|
||||
if is_prime(number):
|
||||
|
||||
ans.append(number)
|
||||
|
||||
# precondition
|
||||
@ -160,14 +155,11 @@ def prime_factorization(number):
|
||||
quotient = number
|
||||
|
||||
if number == 0 or number == 1:
|
||||
|
||||
ans.append(number)
|
||||
|
||||
# if 'number' not prime then builds the prime factorization of 'number'
|
||||
elif not is_prime(number):
|
||||
|
||||
while quotient != 1:
|
||||
|
||||
if is_prime(factor) and (quotient % factor == 0):
|
||||
ans.append(factor)
|
||||
quotient /= factor
|
||||
@ -298,11 +290,9 @@ def goldbach(number):
|
||||
loop = True
|
||||
|
||||
while i < len_pn and loop:
|
||||
|
||||
j = i + 1
|
||||
|
||||
while j < len_pn and loop:
|
||||
|
||||
if prime_numbers[i] + prime_numbers[j] == number:
|
||||
loop = False
|
||||
ans.append(prime_numbers[i])
|
||||
@ -345,7 +335,6 @@ def gcd(number1, number2):
|
||||
rest = 0
|
||||
|
||||
while number2 != 0:
|
||||
|
||||
rest = number1 % number2
|
||||
number1 = number2
|
||||
number2 = rest
|
||||
@ -380,13 +369,11 @@ def kg_v(number1, number2):
|
||||
|
||||
# for kgV (x,1)
|
||||
if number1 > 1 and number2 > 1:
|
||||
|
||||
# builds the prime factorization of 'number1' and 'number2'
|
||||
prime_fac_1 = prime_factorization(number1)
|
||||
prime_fac_2 = prime_factorization(number2)
|
||||
|
||||
elif number1 == 1 or number2 == 1:
|
||||
|
||||
prime_fac_1 = []
|
||||
prime_fac_2 = []
|
||||
ans = max(number1, number2)
|
||||
@ -398,11 +385,8 @@ def kg_v(number1, number2):
|
||||
|
||||
# iterates through primeFac1
|
||||
for n in prime_fac_1:
|
||||
|
||||
if n not in done:
|
||||
|
||||
if n in prime_fac_2:
|
||||
|
||||
count1 = prime_fac_1.count(n)
|
||||
count2 = prime_fac_2.count(n)
|
||||
|
||||
@ -410,7 +394,6 @@ def kg_v(number1, number2):
|
||||
ans *= n
|
||||
|
||||
else:
|
||||
|
||||
count1 = prime_fac_1.count(n)
|
||||
|
||||
for _ in range(count1):
|
||||
@ -420,9 +403,7 @@ def kg_v(number1, number2):
|
||||
|
||||
# iterates through primeFac2
|
||||
for n in prime_fac_2:
|
||||
|
||||
if n not in done:
|
||||
|
||||
count2 = prime_fac_2.count(n)
|
||||
|
||||
for _ in range(count2):
|
||||
@ -455,7 +436,6 @@ def get_prime(n):
|
||||
ans = 2 # this variable holds the answer
|
||||
|
||||
while index < n:
|
||||
|
||||
index += 1
|
||||
|
||||
ans += 1 # counts to the next number
|
||||
@ -499,7 +479,6 @@ def get_primes_between(p_number_1, p_number_2):
|
||||
number += 1
|
||||
|
||||
while number < p_number_2:
|
||||
|
||||
ans.append(number)
|
||||
|
||||
number += 1
|
||||
@ -534,7 +513,6 @@ def get_divisors(n):
|
||||
ans = [] # will be returned.
|
||||
|
||||
for divisor in range(1, n + 1):
|
||||
|
||||
if n % divisor == 0:
|
||||
ans.append(divisor)
|
||||
|
||||
@ -638,7 +616,6 @@ def fib(n):
|
||||
ans = 1 # this will be return
|
||||
|
||||
for _ in range(n - 1):
|
||||
|
||||
tmp = ans
|
||||
ans += fib1
|
||||
fib1 = tmp
|
||||
|
@ -25,7 +25,6 @@ def sieve(n: int) -> list[int]:
|
||||
while low <= n:
|
||||
temp = [True] * (high - low + 1)
|
||||
for each in in_prime:
|
||||
|
||||
t = math.floor(low / each) * each
|
||||
if t < low:
|
||||
t += each
|
||||
|
@ -43,7 +43,6 @@ def two_pointer(nums: list[int], target: int) -> list[int]:
|
||||
j = len(nums) - 1
|
||||
|
||||
while i < j:
|
||||
|
||||
if nums[i] + nums[j] == target:
|
||||
return [i, j]
|
||||
elif nums[i] + nums[j] < target:
|
||||
|
@ -3,7 +3,6 @@ import datetime
|
||||
|
||||
|
||||
def zeller(date_input: str) -> str:
|
||||
|
||||
"""
|
||||
Zellers Congruence Algorithm
|
||||
Find the day of the week for nearly any Gregorian or Julian calendar date
|
||||
|
@ -59,7 +59,6 @@ def largest_square_area_in_matrix_top_down_approch(
|
||||
"""
|
||||
|
||||
def update_area_of_max_square(row: int, col: int) -> int:
|
||||
|
||||
# BASE CASE
|
||||
if row >= rows or col >= cols:
|
||||
return 0
|
||||
@ -138,7 +137,6 @@ def largest_square_area_in_matrix_bottom_up(
|
||||
largest_square_area = 0
|
||||
for row in range(rows - 1, -1, -1):
|
||||
for col in range(cols - 1, -1, -1):
|
||||
|
||||
right = dp_array[row][col + 1]
|
||||
diagonal = dp_array[row + 1][col + 1]
|
||||
bottom = dp_array[row + 1][col]
|
||||
@ -169,7 +167,6 @@ def largest_square_area_in_matrix_bottom_up_space_optimization(
|
||||
largest_square_area = 0
|
||||
for row in range(rows - 1, -1, -1):
|
||||
for col in range(cols - 1, -1, -1):
|
||||
|
||||
right = current_row[col + 1]
|
||||
diagonal = next_row[col + 1]
|
||||
bottom = next_row[col]
|
||||
|
@ -25,7 +25,6 @@ def print_max_activities(start: list[int], finish: list[int]) -> None:
|
||||
|
||||
# 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
|
||||
|
@ -15,14 +15,12 @@ brackets and returns true if S is nested and false otherwise.
|
||||
|
||||
|
||||
def is_balanced(s):
|
||||
|
||||
stack = []
|
||||
open_brackets = set({"(", "[", "{"})
|
||||
closed_brackets = set({")", "]", "}"})
|
||||
open_to_closed = dict({"{": "}", "[": "]", "(": ")"})
|
||||
|
||||
for i in range(len(s)):
|
||||
|
||||
if s[i] in open_brackets:
|
||||
stack.append(s[i])
|
||||
|
||||
|
@ -26,7 +26,6 @@ Thus the weights for each column are as follows:
|
||||
def procentual_proximity(
|
||||
source_data: list[list[float]], weights: list[int]
|
||||
) -> list[list[float]]:
|
||||
|
||||
"""
|
||||
weights - int list
|
||||
possible values - 0 / 1
|
||||
|
@ -54,7 +54,6 @@ def function(expansion, s0, s1, key, message):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
key = input("Enter 10 bit key: ")
|
||||
message = input("Enter 8 bit message: ")
|
||||
|
||||
|
@ -47,7 +47,6 @@ SPEED_OF_LIGHT = 3e8 # unit of c : m * s^-1
|
||||
|
||||
|
||||
def casimir_force(force: float, area: float, distance: float) -> dict[str, float]:
|
||||
|
||||
"""
|
||||
Input Parameters
|
||||
----------------
|
||||
|
@ -34,7 +34,6 @@ def hubble_parameter(
|
||||
dark_energy: float,
|
||||
redshift: float,
|
||||
) -> float:
|
||||
|
||||
"""
|
||||
Input Parameters
|
||||
----------------
|
||||
|
@ -1,39 +1,33 @@
|
||||
"""
|
||||
Lorentz transformation describes the transition from a reference frame P
|
||||
to another reference frame P', each of which is moving in a direction with
|
||||
respect to the other. The Lorentz transformation implemented in this code
|
||||
is the relativistic version using a four vector described by Minkowsky Space:
|
||||
x0 = ct, x1 = x, x2 = y, and x3 = z
|
||||
Lorentz transformations describe the transition between two inertial reference
|
||||
frames F and F', each of which is moving in some direction with respect to the
|
||||
other. This code only calculates Lorentz transformations for movement in the x
|
||||
direction with no spacial rotation (i.e., a Lorentz boost in the x direction).
|
||||
The Lorentz transformations are calculated here as linear transformations of
|
||||
four-vectors [ct, x, y, z] described by Minkowski space. Note that t (time) is
|
||||
multiplied by c (the speed of light) in the first entry of each four-vector.
|
||||
|
||||
NOTE: Please note that x0 is c (speed of light) times t (time).
|
||||
Thus, if X = [ct; x; y; z] and X' = [ct'; x'; y'; z'] are the four-vectors for
|
||||
two inertial reference frames and X' moves in the x direction with velocity v
|
||||
with respect to X, then the Lorentz transformation from X to X' is X' = BX,
|
||||
where
|
||||
|
||||
So, the Lorentz transformation using a four vector is defined as:
|
||||
| γ -γβ 0 0|
|
||||
B = |-γβ γ 0 0|
|
||||
| 0 0 1 0|
|
||||
| 0 0 0 1|
|
||||
|
||||
|ct'| | γ -γβ 0 0| |ct|
|
||||
|x' | = |-γβ γ 0 0| *|x |
|
||||
|y' | | 0 0 1 0| |y |
|
||||
|z' | | 0 0 0 1| |z |
|
||||
|
||||
Where:
|
||||
1
|
||||
γ = ---------------
|
||||
-----------
|
||||
/ v^2 |
|
||||
/(1 - ---
|
||||
-/ c^2
|
||||
|
||||
v
|
||||
β = -----
|
||||
c
|
||||
is the matrix describing the Lorentz boost between X and X',
|
||||
γ = 1 / √(1 - v²/c²) is the Lorentz factor, and β = v/c is the velocity as
|
||||
a fraction of c.
|
||||
|
||||
Reference: https://en.wikipedia.org/wiki/Lorentz_transformation
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from math import sqrt
|
||||
|
||||
import numpy as np # type: ignore
|
||||
from sympy import symbols # type: ignore
|
||||
import numpy as np
|
||||
from sympy import symbols
|
||||
|
||||
# Coefficient
|
||||
# Speed of light (m/s)
|
||||
@ -41,79 +35,77 @@ c = 299792458
|
||||
|
||||
# Symbols
|
||||
ct, x, y, z = symbols("ct x y z")
|
||||
ct_p, x_p, y_p, z_p = symbols("ct' x' y' z'")
|
||||
|
||||
|
||||
# Vehicle's speed divided by speed of light (no units)
|
||||
def beta(velocity: float) -> float:
|
||||
"""
|
||||
Calculates β = v/c, the given velocity as a fraction of c
|
||||
>>> beta(c)
|
||||
1.0
|
||||
|
||||
>>> beta(199792458)
|
||||
0.666435904801848
|
||||
|
||||
>>> beta(1e5)
|
||||
0.00033356409519815205
|
||||
|
||||
>>> beta(0.2)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must be greater than 1!
|
||||
ValueError: Speed must be greater than or equal to 1!
|
||||
"""
|
||||
if velocity > c:
|
||||
raise ValueError("Speed must not exceed Light Speed 299,792,458 [m/s]!")
|
||||
|
||||
# Usually the speed u should be much higher than 1 (c order of magnitude)
|
||||
raise ValueError("Speed must not exceed light speed 299,792,458 [m/s]!")
|
||||
elif velocity < 1:
|
||||
raise ValueError("Speed must be greater than 1!")
|
||||
# Usually the speed should be much higher than 1 (c order of magnitude)
|
||||
raise ValueError("Speed must be greater than or equal to 1!")
|
||||
|
||||
return velocity / c
|
||||
|
||||
|
||||
def gamma(velocity: float) -> float:
|
||||
"""
|
||||
Calculate the Lorentz factor γ = 1 / √(1 - v²/c²) for a given velocity
|
||||
>>> gamma(4)
|
||||
1.0000000000000002
|
||||
|
||||
>>> gamma(1e5)
|
||||
1.0000000556325075
|
||||
|
||||
>>> gamma(3e7)
|
||||
1.005044845777813
|
||||
|
||||
>>> gamma(2.8e8)
|
||||
2.7985595722318277
|
||||
|
||||
>>> gamma(299792451)
|
||||
4627.49902669495
|
||||
|
||||
>>> gamma(0.3)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must be greater than 1!
|
||||
|
||||
>>> gamma(2*c)
|
||||
ValueError: Speed must be greater than or equal to 1!
|
||||
>>> gamma(2 * c)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
|
||||
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
|
||||
"""
|
||||
return 1 / (sqrt(1 - beta(velocity) ** 2))
|
||||
return 1 / sqrt(1 - beta(velocity) ** 2)
|
||||
|
||||
|
||||
def transformation_matrix(velocity: float) -> np.array:
|
||||
def transformation_matrix(velocity: float) -> np.ndarray:
|
||||
"""
|
||||
Calculate the Lorentz transformation matrix for movement in the x direction:
|
||||
|
||||
| γ -γβ 0 0|
|
||||
|-γβ γ 0 0|
|
||||
| 0 0 1 0|
|
||||
| 0 0 0 1|
|
||||
|
||||
where γ is the Lorentz factor and β is the velocity as a fraction of c
|
||||
>>> transformation_matrix(29979245)
|
||||
array([[ 1.00503781, -0.10050378, 0. , 0. ],
|
||||
[-0.10050378, 1.00503781, 0. , 0. ],
|
||||
[ 0. , 0. , 1. , 0. ],
|
||||
[ 0. , 0. , 0. , 1. ]])
|
||||
|
||||
>>> transformation_matrix(19979245.2)
|
||||
array([[ 1.00222811, -0.06679208, 0. , 0. ],
|
||||
[-0.06679208, 1.00222811, 0. , 0. ],
|
||||
[ 0. , 0. , 1. , 0. ],
|
||||
[ 0. , 0. , 0. , 1. ]])
|
||||
|
||||
>>> transformation_matrix(1)
|
||||
array([[ 1.00000000e+00, -3.33564095e-09, 0.00000000e+00,
|
||||
0.00000000e+00],
|
||||
@ -123,16 +115,14 @@ def transformation_matrix(velocity: float) -> np.array:
|
||||
0.00000000e+00],
|
||||
[ 0.00000000e+00, 0.00000000e+00, 0.00000000e+00,
|
||||
1.00000000e+00]])
|
||||
|
||||
>>> transformation_matrix(0)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must be greater than 1!
|
||||
|
||||
ValueError: Speed must be greater than or equal to 1!
|
||||
>>> transformation_matrix(c * 1.5)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
|
||||
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
|
||||
"""
|
||||
return np.array(
|
||||
[
|
||||
@ -144,44 +134,39 @@ def transformation_matrix(velocity: float) -> np.array:
|
||||
)
|
||||
|
||||
|
||||
def transform(
|
||||
velocity: float, event: np.array = np.zeros(4), symbolic: bool = True # noqa: B008
|
||||
) -> np.array:
|
||||
def transform(velocity: float, event: np.ndarray | None = None) -> np.ndarray:
|
||||
"""
|
||||
>>> transform(29979245,np.array([1,2,3,4]), False)
|
||||
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
|
||||
Calculate a Lorentz transformation for movement in the x direction given a
|
||||
velocity and a four-vector for an inertial reference frame
|
||||
|
||||
If no four-vector is given, then calculate the transformation symbolically
|
||||
with variables
|
||||
>>> transform(29979245, np.array([1, 2, 3, 4]))
|
||||
array([ 3.01302757e+08, -3.01302729e+07, 3.00000000e+00, 4.00000000e+00])
|
||||
>>> transform(29979245)
|
||||
array([1.00503781498831*ct - 0.100503778816875*x,
|
||||
-0.100503778816875*ct + 1.00503781498831*x, 1.0*y, 1.0*z],
|
||||
dtype=object)
|
||||
|
||||
>>> transform(19879210.2)
|
||||
array([1.0022057787097*ct - 0.066456172618675*x,
|
||||
-0.066456172618675*ct + 1.0022057787097*x, 1.0*y, 1.0*z],
|
||||
dtype=object)
|
||||
|
||||
>>> transform(299792459, np.array([1,1,1,1]))
|
||||
>>> transform(299792459, np.array([1, 1, 1, 1]))
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must not exceed Light Speed 299,792,458 [m/s]!
|
||||
|
||||
>>> transform(-1, np.array([1,1,1,1]))
|
||||
ValueError: Speed must not exceed light speed 299,792,458 [m/s]!
|
||||
>>> transform(-1, np.array([1, 1, 1, 1]))
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
ValueError: Speed must be greater than 1!
|
||||
ValueError: Speed must be greater than or equal to 1!
|
||||
"""
|
||||
# Ensure event is not a vector of zeros
|
||||
if not symbolic:
|
||||
|
||||
# x0 is ct (speed of ligt * time)
|
||||
event[0] = event[0] * c
|
||||
# Ensure event is not empty
|
||||
if event is None:
|
||||
event = np.array([ct, x, y, z]) # Symbolic four vector
|
||||
else:
|
||||
event[0] *= c # x0 is ct (speed of light * time)
|
||||
|
||||
# Symbolic four vector
|
||||
event = np.array([ct, x, y, z])
|
||||
|
||||
return transformation_matrix(velocity).dot(event)
|
||||
return transformation_matrix(velocity) @ event
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@ -197,9 +182,8 @@ if __name__ == "__main__":
|
||||
print(f"y' = {four_vector[2]}")
|
||||
print(f"z' = {four_vector[3]}")
|
||||
|
||||
# Substitute symbols with numerical values:
|
||||
values = np.array([1, 1, 1, 1])
|
||||
sub_dict = {ct: c * values[0], x: values[1], y: values[2], z: values[3]}
|
||||
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(0, 4)]
|
||||
# Substitute symbols with numerical values
|
||||
sub_dict = {ct: c, x: 1, y: 1, z: 1}
|
||||
numerical_vector = [four_vector[i].subs(sub_dict) for i in range(4)]
|
||||
|
||||
print(f"\n{numerical_vector}")
|
||||
|
@ -28,7 +28,6 @@ GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2
|
||||
def gravitational_law(
|
||||
force: float, mass_1: float, mass_2: float, distance: float
|
||||
) -> dict[str, float]:
|
||||
|
||||
"""
|
||||
Input Parameters
|
||||
----------------
|
||||
|
@ -32,12 +32,10 @@ def solution(n: int = 998001) -> int:
|
||||
|
||||
# fetches the next number
|
||||
for number in range(n - 1, 9999, -1):
|
||||
|
||||
str_number = str(number)
|
||||
|
||||
# checks whether 'str_number' is a palindrome.
|
||||
if str_number == str_number[::-1]:
|
||||
|
||||
divisor = 999
|
||||
|
||||
# if 'number' is a product of two 3-digit numbers
|
||||
|
@ -111,7 +111,6 @@ def solution(chain_length: int = 60, number_limit: int = 1000000) -> int:
|
||||
chain_sets_lengths: dict[int, int] = {}
|
||||
|
||||
for start_chain_element in range(1, number_limit):
|
||||
|
||||
# The temporary set will contain the elements of the chain
|
||||
chain_set = set()
|
||||
chain_set_length = 0
|
||||
|
@ -138,5 +138,4 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
print(f"{solution() = }")
|
||||
|
@ -15,7 +15,6 @@ DIGITS_SQUARED = [sum(int(c, 10) ** 2 for c in i.__str__()) for i in range(10000
|
||||
|
||||
|
||||
def next_number(number: int) -> int:
|
||||
|
||||
"""
|
||||
Returns the next number of the chain by adding the square of each digit
|
||||
to form a new number.
|
||||
@ -31,7 +30,6 @@ def next_number(number: int) -> int:
|
||||
|
||||
sum_of_digits_squared = 0
|
||||
while number:
|
||||
|
||||
# Increased Speed Slightly by checking every 5 digits together.
|
||||
sum_of_digits_squared += DIGITS_SQUARED[number % 100000]
|
||||
number //= 100000
|
||||
|
@ -72,7 +72,6 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts
|
||||
counter = number_of_qubits
|
||||
|
||||
for i in range(counter):
|
||||
|
||||
quantum_circuit.h(number_of_qubits - i - 1)
|
||||
counter -= 1
|
||||
for j in range(counter):
|
||||
|
@ -18,7 +18,6 @@ from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, exec
|
||||
def quantum_teleportation(
|
||||
theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2
|
||||
) -> qiskit.result.counts.Counts:
|
||||
|
||||
"""
|
||||
# >>> quantum_teleportation()
|
||||
#{'00': 500, '11': 500} # ideally
|
||||
|
@ -37,7 +37,6 @@ def calculate_turn_around_time(
|
||||
arrival_time.sort()
|
||||
|
||||
while no_of_process > finished_process_count:
|
||||
|
||||
"""
|
||||
If the current time is less than the arrival time of
|
||||
the process that arrives first among the processes that have not been performed,
|
||||
@ -94,7 +93,6 @@ def calculate_waiting_time(
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
no_of_process = 5
|
||||
process_name = ["A", "B", "C", "D", "E"]
|
||||
arrival_time = [1, 2, 3, 4, 5]
|
||||
|
@ -261,7 +261,6 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None
|
||||
def binary_search_by_recursion(
|
||||
sorted_collection: list[int], item: int, left: int, right: int
|
||||
) -> int | None:
|
||||
|
||||
"""Pure implementation of binary search algorithm in Python by recursion
|
||||
|
||||
Be careful collection must be ascending sorted, otherwise result will be
|
||||
|
@ -49,7 +49,6 @@ def interpolation_search(sorted_collection, item):
|
||||
|
||||
|
||||
def interpolation_search_by_recursion(sorted_collection, item, left, right):
|
||||
|
||||
"""Pure implementation of interpolation search algorithm in Python by recursion
|
||||
Be careful collection must be ascending sorted, otherwise result will be
|
||||
unpredictable
|
||||
|
@ -220,7 +220,6 @@ def tabu_search(
|
||||
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]
|
||||
|
@ -103,7 +103,6 @@ def ite_ternary_search(array: list[int], target: int) -> int:
|
||||
left = two_third + 1
|
||||
|
||||
else:
|
||||
|
||||
left = one_third + 1
|
||||
right = two_third - 1
|
||||
else:
|
||||
|
@ -37,7 +37,6 @@ def comb_sort(data: list) -> list:
|
||||
completed = False
|
||||
|
||||
while not completed:
|
||||
|
||||
# Update the gap value for a next comb
|
||||
gap = int(gap / shrink_factor)
|
||||
if gap <= 1:
|
||||
|
@ -30,7 +30,6 @@ def odd_even_sort(input_list: list) -> list:
|
||||
is_sorted = True
|
||||
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
|
||||
if input_list[i] > input_list[i + 1]:
|
||||
|
||||
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
|
||||
# swapping if elements not in order
|
||||
is_sorted = False
|
||||
|
@ -34,7 +34,6 @@ def oe_process(position, value, l_send, r_send, lr_cv, rr_cv, result_pipe):
|
||||
# we *could* stop early if we are sorted already, but it takes as long to
|
||||
# find out we are sorted as it does to sort the list with this algorithm
|
||||
for i in range(0, 10):
|
||||
|
||||
if (i + position) % 2 == 0 and r_send is not None:
|
||||
# send your value to your right neighbor
|
||||
process_lock.acquire()
|
||||
|
@ -19,7 +19,6 @@ def _in_place_quick_sort(a, start, end):
|
||||
|
||||
|
||||
def _in_place_partition(a, start, end):
|
||||
|
||||
count = 0
|
||||
pivot = randint(start, end)
|
||||
temp = a[end]
|
||||
@ -27,7 +26,6 @@ def _in_place_partition(a, start, end):
|
||||
a[pivot] = temp
|
||||
new_pivot_index = start - 1
|
||||
for index in range(start, end):
|
||||
|
||||
count += 1
|
||||
if a[index] < a[end]: # check if current val is less than pivot value
|
||||
new_pivot_index = new_pivot_index + 1
|
||||
|
@ -44,7 +44,6 @@ def shell_sort(collection: list) -> list:
|
||||
|
||||
# Continue sorting until the gap is 1
|
||||
while gap > 1:
|
||||
|
||||
# Decrease the gap value
|
||||
gap = int(gap / shrink)
|
||||
|
||||
|
@ -12,7 +12,6 @@ def stooge_sort(arr):
|
||||
|
||||
|
||||
def stooge(arr, i, h):
|
||||
|
||||
if i >= h:
|
||||
return
|
||||
|
||||
|
@ -73,7 +73,6 @@ def tim_sort(lst):
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
|
||||
sorted_lst = tim_sort(lst)
|
||||
print(sorted_lst)
|
||||
|
@ -2,7 +2,6 @@ import re
|
||||
|
||||
|
||||
def dna(dna: str) -> str:
|
||||
|
||||
"""
|
||||
https://en.wikipedia.org/wiki/DNA
|
||||
Returns the second side of a DNA strand
|
||||
|
@ -35,7 +35,6 @@ def hamming_distance(string1: str, string2: str) -> int:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import doctest
|
||||
|
||||
doctest.testmod()
|
||||
|
@ -44,11 +44,9 @@ def levenshtein_distance(first_word: str, second_word: str) -> int:
|
||||
previous_row = list(range(len(second_word) + 1))
|
||||
|
||||
for i, c1 in enumerate(first_word):
|
||||
|
||||
current_row = [i + 1]
|
||||
|
||||
for j, c2 in enumerate(second_word):
|
||||
|
||||
# Calculate insertions, deletions and substitutions
|
||||
insertions = previous_row[j + 1] + 1
|
||||
deletions = current_row[j] + 1
|
||||
|
@ -29,7 +29,6 @@ def prefix_function(input_string: str) -> list:
|
||||
prefix_result = [0] * len(input_string)
|
||||
|
||||
for i in range(1, len(input_string)):
|
||||
|
||||
# use last results for better performance - dynamic programming
|
||||
j = prefix_result[i - 1]
|
||||
while j > 0 and input_string[i] != input_string[j]:
|
||||
|
@ -33,7 +33,6 @@ def text_justification(word: str, max_width: int) -> list:
|
||||
words = word.split()
|
||||
|
||||
def justify(line: list, width: int, max_width: int) -> str:
|
||||
|
||||
overall_spaces_count = max_width - width
|
||||
words_count = len(line)
|
||||
if len(line) == 1:
|
||||
|
@ -8,7 +8,6 @@ BASE_URL = "https://ww1.gogoanime2.org"
|
||||
|
||||
|
||||
def search_scraper(anime_name: str) -> list:
|
||||
|
||||
"""[summary]
|
||||
|
||||
Take an url and
|
||||
@ -66,7 +65,6 @@ def search_scraper(anime_name: str) -> list:
|
||||
|
||||
|
||||
def search_anime_episode_list(episode_endpoint: str) -> list:
|
||||
|
||||
"""[summary]
|
||||
|
||||
Take an url and
|
||||
@ -116,7 +114,6 @@ def search_anime_episode_list(episode_endpoint: str) -> list:
|
||||
|
||||
|
||||
def get_anime_episode(episode_endpoint: str) -> list:
|
||||
|
||||
"""[summary]
|
||||
|
||||
Get click url and download url from episode url
|
||||
@ -153,7 +150,6 @@ def get_anime_episode(episode_endpoint: str) -> list:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
anime_name = input("Enter anime name: ").strip()
|
||||
anime_list = search_scraper(anime_name)
|
||||
print("\n")
|
||||
@ -161,9 +157,8 @@ if __name__ == "__main__":
|
||||
if len(anime_list) == 0:
|
||||
print("No anime found with this name")
|
||||
else:
|
||||
|
||||
print(f"Found {len(anime_list)} results: ")
|
||||
for (i, anime) in enumerate(anime_list):
|
||||
for i, anime in enumerate(anime_list):
|
||||
anime_title = anime["title"]
|
||||
print(f"{i+1}. {anime_title}")
|
||||
|
||||
@ -176,7 +171,7 @@ if __name__ == "__main__":
|
||||
print("No episode found for this anime")
|
||||
else:
|
||||
print(f"Found {len(episode_list)} results: ")
|
||||
for (i, episode) in enumerate(episode_list):
|
||||
for i, episode in enumerate(episode_list):
|
||||
print(f"{i+1}. {episode['title']}")
|
||||
|
||||
episode_choice = int(input("\nChoose an episode by serial no: ").strip())
|
||||
|
@ -37,7 +37,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
|
||||
"""
|
||||
|
||||
try:
|
||||
|
||||
# Has user provided both inputs?
|
||||
if not drug_name or not zip_code:
|
||||
return None
|
||||
@ -58,7 +57,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
|
||||
grid_list = soup.find_all("div", {"class": "grid-x pharmCard"})
|
||||
if grid_list and len(grid_list) > 0:
|
||||
for grid in grid_list:
|
||||
|
||||
# Get the pharmacy price.
|
||||
pharmacy_name = grid.find("p", {"class": "list-title"}).text
|
||||
|
||||
@ -79,7 +77,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# Enter a drug name and a zip code
|
||||
drug_name = input("Enter drug name: ").strip()
|
||||
zip_code = input("Enter zip code: ").strip()
|
||||
@ -89,10 +86,8 @@ if __name__ == "__main__":
|
||||
)
|
||||
|
||||
if pharmacy_price_list:
|
||||
|
||||
print(f"\nSearch results for {drug_name} at location {zip_code}:")
|
||||
for pharmacy_price in pharmacy_price_list:
|
||||
|
||||
name = pharmacy_price["pharmacy_name"]
|
||||
price = pharmacy_price["price"]
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user