pre-commit: Upgrade psf/black for stable style 2023 (#8110)

* pre-commit: Upgrade psf/black for stable style 2023

Updating https://github.com/psf/black ... updating 22.12.0 -> 23.1.0 for their `2023 stable style`.
* https://github.com/psf/black/blob/main/CHANGES.md#2310

> This is the first [psf/black] release of 2023, and following our stability policy, it comes with a number of improvements to our stable style…

Also, add https://github.com/tox-dev/pyproject-fmt and https://github.com/abravalheri/validate-pyproject to pre-commit.

I only modified `.pre-commit-config.yaml` and all other files were modified by pre-commit.ci and psf/black.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
Christian Clauss 2023-02-01 14:14:54 +01:00 committed by GitHub
parent ed0a581f93
commit c909da9b08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
97 changed files with 19 additions and 154 deletions

View File

@ -15,7 +15,7 @@ repos:
- id: auto-walrus - id: auto-walrus
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 22.12.0 rev: 23.1.0
hooks: hooks:
- id: black - id: black
@ -26,6 +26,16 @@ repos:
args: args:
- --profile=black - --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 - repo: https://github.com/asottile/pyupgrade
rev: v3.3.1 rev: v3.3.1
hooks: hooks:

View File

@ -59,7 +59,6 @@ def newton_raphson(
# Let's Execute # Let's Execute
if __name__ == "__main__": if __name__ == "__main__":
# Find root of trigonometric function # Find root of trigonometric function
# Find value of pi # Find value of pi
print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") print(f"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}")

View File

@ -107,7 +107,6 @@ def depth_first_search(
# We iterate each column in the row to find all possible results in each row # We iterate each column in the row to find all possible results in each row
for col in range(n): for col in range(n):
# We apply that we learned previously. First we check that in the current board # 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 # (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 # that there are a collision in vertical. Then we apply the two formulas we

View File

@ -53,6 +53,7 @@ def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int:
# ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid----------------
# This function find the inverses of a i.e., a^(-1) # This function find the inverses of a i.e., a^(-1)
def invert_modulo(a: int, n: int) -> int: def invert_modulo(a: int, n: int) -> int:
""" """

View File

@ -230,7 +230,6 @@ def enigma(
# encryption/decryption process -------------------------- # encryption/decryption process --------------------------
for symbol in text: for symbol in text:
if symbol in abc: if symbol in abc:
# 1st plugboard -------------------------- # 1st plugboard --------------------------
if symbol in plugboard: if symbol in plugboard:
symbol = plugboard[symbol] symbol = plugboard[symbol]

View File

@ -39,7 +39,6 @@ def prepare_input(dirty: str) -> str:
def generate_table(key: str) -> list[str]: def generate_table(key: str) -> list[str]:
# I and J are used interchangeably to allow # I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters) # us to use a 5x5 table (25 letters)
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ" alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"

View File

@ -19,7 +19,6 @@ SQUARE = [
class PolybiusCipher: class PolybiusCipher:
def __init__(self) -> None: def __init__(self) -> None:
self.SQUARE = np.array(SQUARE) self.SQUARE = np.array(SQUARE)
def letter_to_numbers(self, letter: str) -> np.ndarray: def letter_to_numbers(self, letter: str) -> np.ndarray:

View File

@ -130,7 +130,6 @@ class XORCipher:
try: try:
with open(file) as fin: with open(file) as fin:
with open("encrypt.out", "w+") as fout: with open("encrypt.out", "w+") as fout:
# actual encrypt-process # actual encrypt-process
for line in fin: for line in fin:
fout.write(self.encrypt_string(line, key)) fout.write(self.encrypt_string(line, key))
@ -155,7 +154,6 @@ class XORCipher:
try: try:
with open(file) as fin: with open(file) as fin:
with open("decrypt.out", "w+") as fout: with open("decrypt.out", "w+") as fout:
# actual encrypt-process # actual encrypt-process
for line in fin: for line in fin:
fout.write(self.decrypt_string(line, key)) fout.write(self.decrypt_string(line, key))

View File

@ -89,7 +89,6 @@ class LZ77Compressor:
# while there are still characters in text to compress # while there are still characters in text to compress
while text: while text:
# find the next encoding phrase # find the next encoding phrase
# - triplet with offset, length, indicator (the next encoding character) # - triplet with offset, length, indicator (the next encoding character)
token = self._find_encoding_token(text, search_buffer) token = self._find_encoding_token(text, search_buffer)

View File

@ -28,7 +28,6 @@ import tensorflow as tf
from tensorflow.keras import layers, models from tensorflow.keras import layers, models
if __name__ == "__main__": if __name__ == "__main__":
# Initialising the CNN # Initialising the CNN
# (Sequential- Building the model layer by layer) # (Sequential- Building the model layer by layer)
classifier = models.Sequential() classifier = models.Sequential()

View File

@ -9,7 +9,6 @@ https://en.wikipedia.org/wiki/Harris_Corner_Detector
class HarrisCorner: class HarrisCorner:
def __init__(self, k: float, window_size: int): def __init__(self, k: float, window_size: int):
""" """
k : is an empirically determined constant in [0.04,0.06] k : is an empirically determined constant in [0.04,0.06]
window_size : neighbourhoods considered window_size : neighbourhoods considered
@ -25,7 +24,6 @@ class HarrisCorner:
return str(self.k) return str(self.k)
def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:
""" """
Returns the image with corners identified Returns the image with corners identified
img_path : path of the image img_path : path of the image
@ -68,7 +66,6 @@ class HarrisCorner:
if __name__ == "__main__": if __name__ == "__main__":
edge_detect = HarrisCorner(0.04, 3) edge_detect = HarrisCorner(0.04, 3)
color_img, _ = edge_detect.detect("path_to_image") color_img, _ = edge_detect.detect("path_to_image")
cv2.imwrite("detect.png", color_img) cv2.imwrite("detect.png", color_img)

View File

@ -2,7 +2,6 @@
def decimal_to_binary(num: int) -> str: def decimal_to_binary(num: int) -> str:
""" """
Convert an Integer Decimal Number to a Binary Number as str. Convert an Integer Decimal Number to a Binary Number as str.
>>> decimal_to_binary(0) >>> decimal_to_binary(0)

View File

@ -86,7 +86,6 @@ def pressure_and_volume_to_temperature(
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -47,7 +47,7 @@ def int_to_roman(number: int) -> str:
True True
""" """
result = [] result = []
for (arabic, roman) in ROMAN: for arabic, roman in ROMAN:
(factor, number) = divmod(number, arabic) (factor, number) = divmod(number, arabic)
result.append(roman * factor) result.append(roman * factor)
if number == 0: if number == 0:

View File

@ -380,7 +380,6 @@ def reaumur_to_rankine(reaumur: float, ndigits: int = 2) -> float:
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -307,7 +307,6 @@ def weight_conversion(from_type: str, to_type: str, value: float) -> float:
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -105,7 +105,6 @@ def get_nodes_from_left_to_right(
if not root: if not root:
return return
if level == 1: if level == 1:
output.append(root.data) output.append(root.data)
elif level > 1: elif level > 1:
populate_output(root.left, level - 1) populate_output(root.left, level - 1)

View File

@ -58,7 +58,6 @@ def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return
def make_tree() -> BinaryTreeNode | None: def make_tree() -> BinaryTreeNode | None:
root = insert(None, 15) root = insert(None, 15)
insert(root, 10) insert(root, 10)
insert(root, 25) insert(root, 25)

View File

@ -24,7 +24,6 @@ class DoubleHash(HashTable):
super().__init__(*args, **kwargs) super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data): def __hash_function_2(self, value, data):
next_prime_gt = ( next_prime_gt = (
next_prime(value % self.size_table) next_prime(value % self.size_table)
if not is_prime(value % self.size_table) if not is_prime(value % self.size_table)

View File

@ -32,7 +32,6 @@ class HashTable:
return key % self.size_table return key % self.size_table
def _step_by_step(self, step_ord): def _step_by_step(self, step_ord):
print(f"step {step_ord}") print(f"step {step_ord}")
print(list(range(len(self.values)))) print(list(range(len(self.values))))
print(self.values) print(self.values)
@ -53,7 +52,6 @@ class HashTable:
new_key = self.hash_function(key + 1) new_key = self.hash_function(key + 1)
while self.values[new_key] is not None and self.values[new_key] != key: while self.values[new_key] is not None and self.values[new_key] != key:
if self.values.count(None) > 0: if self.values.count(None) > 0:
new_key = self.hash_function(new_key + 1) new_key = self.hash_function(new_key + 1)
else: else:

View File

@ -174,7 +174,6 @@ class BinomialHeap:
i.left_tree_size == i.parent.left_tree_size i.left_tree_size == i.parent.left_tree_size
and i.left_tree_size != i.parent.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size
): ):
# Neighbouring Nodes # Neighbouring Nodes
previous_node = i.left previous_node = i.left
next_node = i.parent.parent next_node = i.parent.parent
@ -233,7 +232,6 @@ class BinomialHeap:
and self.bottom_root.left_tree_size and self.bottom_root.left_tree_size
== self.bottom_root.parent.left_tree_size == self.bottom_root.parent.left_tree_size
): ):
# Next node # Next node
next_node = self.bottom_root.parent.parent next_node = self.bottom_root.parent.parent

View File

@ -71,7 +71,6 @@ class SkewHeap(Generic[T]):
""" """
def __init__(self, data: Iterable[T] | None = ()) -> None: def __init__(self, data: Iterable[T] | None = ()) -> None:
""" """
>>> sh = SkewHeap([3, 1, 3, 7]) >>> sh = SkewHeap([3, 1, 3, 7])
>>> list(sh) >>> list(sh)

View File

@ -80,7 +80,6 @@ class LinkedList:
return None return None
def set_head(self, node: Node) -> None: def set_head(self, node: Node) -> None:
if self.head is None: if self.head is None:
self.head = node self.head = node
self.tail = node self.tail = node
@ -143,7 +142,6 @@ class LinkedList:
raise Exception("Node not found") raise Exception("Node not found")
def delete_value(self, value): def delete_value(self, value):
if (node := self.get_node(value)) is not None: if (node := self.get_node(value)) is not None:
if node == self.head: if node == self.head:
self.head = self.head.get_next() self.head = self.head.get_next()

View File

@ -36,7 +36,6 @@ def evaluate(expression):
# iterate over the string in reverse order # iterate over the string in reverse order
for c in expression.split()[::-1]: for c in expression.split()[::-1]:
# push operand to stack # push operand to stack
if is_operand(c): if is_operand(c):
stack.append(int(c)) stack.append(int(c))

View File

@ -92,7 +92,6 @@ class Stack(Generic[T]):
# Code execution starts here # Code execution starts here
if __name__ == "__main__": if __name__ == "__main__":
# Start with the empty stack # Start with the empty stack
stack: Stack[int] = Stack() stack: Stack[int] = Stack()

View File

@ -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): def calculation_span(price, s):
n = len(price) n = len(price)
# Create a stack and push index of fist element to it # Create a stack and push index of fist element to it
st = [] st = []
@ -20,7 +19,6 @@ def calculation_span(price, s):
# Calculate span values for rest of the elements # Calculate span values for rest of the elements
for i in range(1, n): for i in range(1, n):
# Pop elements from stack while stack is not # Pop elements from stack while stack is not
# empty and top of stack is smaller than price[i] # empty and top of stack is smaller than price[i]
while len(st) > 0 and price[st[0]] <= price[i]: while len(st) > 0 and price[st[0]] <= price[i]:

View File

@ -50,7 +50,6 @@ def bilateral_filter(
size_x, size_y = img.shape size_x, size_y = img.shape
for i in range(kernel_size // 2, size_x - kernel_size // 2): for i in range(kernel_size // 2, size_x - kernel_size // 2):
for j in range(kernel_size // 2, size_y - 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_s = get_slice(img, i, j, kernel_size)
img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_i = img_s - img_s[kernel_size // 2, kernel_size // 2]
img_ig = vec_gaussian(img_i, intensity_variance) img_ig = vec_gaussian(img_i, intensity_variance)

View File

@ -61,7 +61,6 @@ def local_binary_value(image: np.ndarray, x_coordinate: int, y_coordinate: int)
if __name__ == "__main__": if __name__ == "__main__":
# Reading the image and converting it to grayscale. # Reading the image and converting it to grayscale.
image = cv2.imread( image = cv2.imread(
"digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE "digital_image_processing/image_data/lena.jpg", cv2.IMREAD_GRAYSCALE

View File

@ -13,7 +13,6 @@ from collections import defaultdict
class AssignmentUsingBitmask: class AssignmentUsingBitmask:
def __init__(self, task_performed, total): def __init__(self, task_performed, total):
self.total_tasks = total # total no of tasks (N) self.total_tasks = total # total no of tasks (N)
# DP table will have a dimension of (2^M)*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 self.final_mask = (1 << len(task_performed)) - 1
def count_ways_until(self, mask, task_no): def count_ways_until(self, mask, task_no):
# if mask == self.finalmask all persons are distributed tasks, return 1 # if mask == self.finalmask all persons are distributed tasks, return 1
if mask == self.final_mask: if mask == self.final_mask:
return 1 return 1
@ -49,7 +47,6 @@ class AssignmentUsingBitmask:
# assign for the remaining tasks. # assign for the remaining tasks.
if task_no in self.task: if task_no in self.task:
for p in self.task[task_no]: for p in self.task[task_no]:
# if p is already given a task # if p is already given a task
if mask & (1 << p): if mask & (1 << p):
continue continue
@ -64,7 +61,6 @@ class AssignmentUsingBitmask:
return self.dp[mask][task_no] return self.dp[mask][task_no]
def count_no_of_ways(self, task_performed): def count_no_of_ways(self, task_performed):
# Store the list of persons for each task # Store the list of persons for each task
for i in range(len(task_performed)): for i in range(len(task_performed)):
for j in task_performed[i]: for j in task_performed[i]:
@ -75,7 +71,6 @@ class AssignmentUsingBitmask:
if __name__ == "__main__": if __name__ == "__main__":
total_tasks = 5 # total no of tasks (the value of N) total_tasks = 5 # total no of tasks (the value of N)
# the list of tasks that can be done by M persons. # the list of tasks that can be done by M persons.

View File

@ -9,7 +9,6 @@ from __future__ import annotations
def list_of_submasks(mask: int) -> list[int]: def list_of_submasks(mask: int) -> list[int]:
""" """
Args: Args:
mask : number which shows mask ( always integer > 0, zero does not have any mask : number which shows mask ( always integer > 0, zero does not have any

View File

@ -8,7 +8,6 @@ COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2
def couloumbs_law( def couloumbs_law(
force: float, charge1: float, charge2: float, distance: float force: float, charge1: float, charge2: float, distance: float
) -> dict[str, float]: ) -> dict[str, float]:
""" """
Apply Coulomb's Law on any three given values. These can be force, charge1, 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 charge2, or distance, and then in a Python dict return name/value pair of

View File

@ -170,7 +170,6 @@ def ignore_overflow_warnings() -> None:
if __name__ == "__main__": if __name__ == "__main__":
z_0 = prepare_grid(window_size, nb_pixels) z_0 = prepare_grid(window_size, nb_pixels)
ignore_overflow_warnings() # See file header for explanations ignore_overflow_warnings() # See file header for explanations

View File

@ -114,7 +114,6 @@ def get_image(
# loop through the image-coordinates # loop through the image-coordinates
for image_x in range(image_width): for image_x in range(image_width):
for image_y in range(image_height): for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates # determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width

View File

@ -10,7 +10,6 @@ EQUATORIAL_RADIUS = 6378137
def lamberts_ellipsoidal_distance( def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float lat1: float, lon1: float, lat2: float, lon2: float
) -> float: ) -> float:
""" """
Calculate the shortest distance along the surface of an ellipsoid between Calculate the shortest distance along the surface of an ellipsoid between
two points on the surface of earth given longitudes and latitudes two points on the surface of earth given longitudes and latitudes

View File

@ -16,7 +16,6 @@ def search(
cost: int, cost: int,
heuristic: list[list[int]], heuristic: list[list[int]],
) -> tuple[list[list[int]], list[list[int]]]: ) -> tuple[list[list[int]], list[list[int]]]:
closed = [ closed = [
[0 for col in range(len(grid[0]))] for row in range(len(grid)) [0 for col in range(len(grid[0]))] for row in range(len(grid))
] # the reference grid ] # the reference grid

View File

@ -20,7 +20,6 @@ def check_bipartite(graph):
visited[u] = True visited[u] = True
for neighbour in graph[u]: for neighbour in graph[u]:
if neighbour == u: if neighbour == u:
return False return False

View File

@ -8,7 +8,6 @@ class Graph:
self.graph[v - 1][u - 1] = 1 self.graph[v - 1][u - 1] = 1
def show(self): def show(self):
for i in self.graph: for i in self.graph:
for j in i: for j in i:
print(j, end=" ") print(j, end=" ")

View File

@ -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} graph_copy = {node: graph[node][:] for node in graph}
while len(graph_copy) > 2: while len(graph_copy) > 2:
# Choose a random edge. # Choose a random edge.
u = random.choice(list(graph_copy.keys())) u = random.choice(list(graph_copy.keys()))
v = random.choice(graph_copy[u]) v = random.choice(graph_copy[u])

View File

@ -4,7 +4,6 @@ class Graph:
""" """
def __init__(self): def __init__(self):
self.num_vertices = 0 self.num_vertices = 0
self.num_edges = 0 self.num_edges = 0
self.adjacency = {} self.adjacency = {}

View File

@ -33,7 +33,7 @@ class PriorityQueue:
temp.append((pri, x)) temp.append((pri, x))
(pri, x) = heapq.heappop(self.elements) (pri, x) = heapq.heappop(self.elements)
temp.append((priority, item)) temp.append((priority, item))
for (pro, xxx) in temp: for pro, xxx in temp:
heapq.heappush(self.elements, (pro, xxx)) heapq.heappush(self.elements, (pro, xxx))
def remove_element(self, item): def remove_element(self, item):
@ -44,7 +44,7 @@ class PriorityQueue:
while x != item: while x != item:
temp.append((pro, x)) temp.append((pro, x))
(pro, x) = heapq.heappop(self.elements) (pro, x) = heapq.heappop(self.elements)
for (prito, yyy) in temp: for prito, yyy in temp:
heapq.heappush(self.elements, (prito, yyy)) heapq.heappush(self.elements, (prito, yyy))
def top_show(self): def top_show(self):

View File

@ -46,7 +46,6 @@ def knapsack(
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -115,7 +115,6 @@ def conjugate_gradient(
iterations = 0 iterations = 0
while error > tol: while error > tol:
# Save this value so we only calculate the matrix-vector product once. # Save this value so we only calculate the matrix-vector product once.
w = np.dot(spd_matrix, p0) w = np.dot(spd_matrix, p0)

View File

@ -74,7 +74,6 @@ def centroid_pairwise_dist(x, centroids):
def assign_clusters(data, centroids): def assign_clusters(data, centroids):
# Compute distances between each data point and the set of centroids: # Compute distances between each data point and the set of centroids:
# Fill in the blank (RHS only) # Fill in the blank (RHS only)
distances_from_centroids = centroid_pairwise_dist(data, centroids) 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): def compute_heterogeneity(data, k, centroids, cluster_assignment):
heterogeneity = 0.0 heterogeneity = 0.0
for i in range(k): for i in range(k):
# Select all data points that belong to cluster i. Fill in the blank (RHS only) # Select all data points that belong to cluster i. Fill in the blank (RHS only)
member_data_points = data[cluster_assignment == i, :] member_data_points = data[cluster_assignment == i, :]

View File

@ -49,7 +49,6 @@ def main() -> None:
for _ in range(epochs): for _ in range(epochs):
for j in range(len(training_samples)): for j in range(len(training_samples)):
# training sample # training sample
sample = training_samples[j] sample = training_samples[j]

View File

@ -82,7 +82,6 @@ class SmoSVM:
k = self._k k = self._k
state = None state = None
while True: while True:
# 1: Find alpha1, alpha2 # 1: Find alpha1, alpha2
try: try:
i1, i2 = self.choose_alpha.send(state) i1, i2 = self.choose_alpha.send(state)
@ -146,7 +145,6 @@ class SmoSVM:
# Predict test samples # Predict test samples
def predict(self, test_samples, classify=True): def predict(self, test_samples, classify=True):
if test_samples.shape[1] > self.samples.shape[1]: if test_samples.shape[1] > self.samples.shape[1]:
raise ValueError( raise ValueError(
"Test samples' feature length does not equal to that of train samples" "Test samples' feature length does not equal to that of train samples"

View File

@ -41,7 +41,6 @@ def xgboost(features: np.ndarray, target: np.ndarray) -> XGBClassifier:
def main() -> None: def main() -> None:
""" """
>>> main() >>> main()

View File

@ -62,7 +62,7 @@ def pluperfect_number(n: int) -> bool:
digit_histogram[rem] += 1 digit_histogram[rem] += 1
digit_total += 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 total += cnt * i**digit_total
return n == total return n == total

View File

@ -5,7 +5,6 @@
def binary_exponentiation(a, n): def binary_exponentiation(a, n):
if n == 0: if n == 0:
return 1 return 1

View File

@ -39,7 +39,6 @@ def combinations(n: int, k: int) -> int:
if __name__ == "__main__": if __name__ == "__main__":
print( print(
"The number of five-card hands possible from a standard", "The number of five-card hands possible from a standard",
f"fifty-two card deck is: {combinations(52, 5)}\n", f"fifty-two card deck is: {combinations(52, 5)}\n",

View File

@ -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: def decimal_isolate(number: float, digit_amount: int) -> float:
""" """
Isolates the decimal part of a number. Isolates the decimal part of a number.
If digitAmount > 0 round to that decimal place, else print the entire decimal. If digitAmount > 0 round to that decimal place, else print the entire decimal.

View File

@ -6,7 +6,6 @@
def binary_exponentiation(a, n, mod): def binary_exponentiation(a, n, mod):
if n == 0: if n == 0:
return 1 return 1

View File

@ -62,7 +62,6 @@ def find_minimum_change(denominations: list[int], value: str) -> list[int]:
# Traverse through all denomination # Traverse through all denomination
for denomination in reversed(denominations): for denomination in reversed(denominations):
# Find denominations # Find denominations
while int(total_value) >= int(denomination): while int(total_value) >= int(denomination):
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 # Driver Code
if __name__ == "__main__": if __name__ == "__main__":
denominations = [] denominations = []
value = "0" value = "0"

View File

@ -35,7 +35,6 @@ xn = b
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float: def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
""" """
Args: Args:
function : the function which's integration is desired function : the function which's integration is desired

View File

@ -51,7 +51,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
""" """
if isinstance(set_a, set) and isinstance(set_b, set): if isinstance(set_a, set) and isinstance(set_b, set):
intersection = len(set_a.intersection(set_b)) intersection = len(set_a.intersection(set_b))
if alternative_union: if alternative_union:
@ -62,7 +61,6 @@ def jaccard_similarity(set_a, set_b, alternative_union=False):
return intersection / union return intersection / union
if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)): if isinstance(set_a, (list, tuple)) and isinstance(set_b, (list, tuple)):
intersection = [element for element in set_a if element in set_b] intersection = [element for element in set_a if element in set_b]
if alternative_union: if alternative_union:

View File

@ -67,7 +67,6 @@ def benchmark():
class TestLeastCommonMultiple(unittest.TestCase): class TestLeastCommonMultiple(unittest.TestCase):
test_inputs = [ test_inputs = [
(10, 20), (10, 20),
(13, 15), (13, 15),

View File

@ -10,7 +10,6 @@ def line_length(
x_end: int | float, x_end: int | float,
steps: int = 100, steps: int = 100,
) -> float: ) -> float:
""" """
Approximates the arc length of a line segment by treating the curve as a Approximates the arc length of a line segment by treating the curve as a
sequence of linear lines and summing their lengths sequence of linear lines and summing their lengths
@ -41,7 +40,6 @@ def line_length(
length = 0.0 length = 0.0
for _ in range(steps): for _ in range(steps):
# Approximates curve as a sequence of linear lines and sums their length # Approximates curve as a sequence of linear lines and sums their length
x2 = (x_end - x_start) / steps + x1 x2 = (x_end - x_start) / steps + x1
fx2 = fnc(x2) fx2 = fnc(x2)

View File

@ -18,6 +18,7 @@ def pi_estimator(iterations: int):
5. Multiply this value by 4 to get your estimate of pi. 5. Multiply this value by 4 to get your estimate of pi.
6. Print the estimated and numpy value of pi 6. Print the estimated and numpy value of pi
""" """
# A local function to see if a dot lands in the circle. # A local function to see if a dot lands in the circle.
def is_in_circle(x: float, y: float) -> bool: def is_in_circle(x: float, y: float) -> bool:
distance_from_centre = sqrt((x**2) + (y**2)) distance_from_centre = sqrt((x**2) + (y**2))

View File

@ -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): def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6, logsteps=False):
a = x0 # set the initial guess a = x0 # set the initial guess
steps = [a] steps = [a]
error = abs(f(a)) error = abs(f(a))

View File

@ -12,7 +12,6 @@ def trapezoidal_area(
x_end: int | float, x_end: int | float,
steps: int = 100, steps: int = 100,
) -> float: ) -> float:
""" """
Treats curve as a collection of linear lines and sums the area of the Treats curve as a collection of linear lines and sums the area of the
trapezium shape they form trapezium shape they form
@ -40,7 +39,6 @@ def trapezoidal_area(
area = 0.0 area = 0.0
for _ in range(steps): for _ in range(steps):
# Approximates small segments of curve as linear and solve # Approximates small segments of curve as linear and solve
# for trapezoidal area # for trapezoidal area
x2 = (x_end - x_start) / steps + x1 x2 = (x_end - x_start) / steps + x1

View File

@ -59,7 +59,6 @@ def is_prime(number: int) -> bool:
status = False status = False
for divisor in range(2, int(round(sqrt(number))) + 1): for divisor in range(2, int(round(sqrt(number))) + 1):
# if 'number' divisible by 'divisor' then sets 'status' # if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop. # of false and break up the loop.
if number % divisor == 0: if number % divisor == 0:
@ -95,9 +94,7 @@ def sieve_er(n):
# actual sieve of erathostenes # actual sieve of erathostenes
for i in range(len(begin_list)): for i in range(len(begin_list)):
for j in range(i + 1, 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): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
begin_list[j] = 0 begin_list[j] = 0
@ -128,9 +125,7 @@ def get_prime_numbers(n):
# iterates over all numbers between 2 up to N+1 # iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans' # if a number is prime then appends to list 'ans'
for number in range(2, n + 1): for number in range(2, n + 1):
if is_prime(number): if is_prime(number):
ans.append(number) ans.append(number)
# precondition # precondition
@ -160,14 +155,11 @@ def prime_factorization(number):
quotient = number quotient = number
if number == 0 or number == 1: if number == 0 or number == 1:
ans.append(number) ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number' # if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(number): elif not is_prime(number):
while quotient != 1: while quotient != 1:
if is_prime(factor) and (quotient % factor == 0): if is_prime(factor) and (quotient % factor == 0):
ans.append(factor) ans.append(factor)
quotient /= factor quotient /= factor
@ -298,11 +290,9 @@ def goldbach(number):
loop = True loop = True
while i < len_pn and loop: while i < len_pn and loop:
j = i + 1 j = i + 1
while j < len_pn and loop: while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number: if prime_numbers[i] + prime_numbers[j] == number:
loop = False loop = False
ans.append(prime_numbers[i]) ans.append(prime_numbers[i])
@ -345,7 +335,6 @@ def gcd(number1, number2):
rest = 0 rest = 0
while number2 != 0: while number2 != 0:
rest = number1 % number2 rest = number1 % number2
number1 = number2 number1 = number2
number2 = rest number2 = rest
@ -380,13 +369,11 @@ def kg_v(number1, number2):
# for kgV (x,1) # for kgV (x,1)
if number1 > 1 and number2 > 1: if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2' # builds the prime factorization of 'number1' and 'number2'
prime_fac_1 = prime_factorization(number1) prime_fac_1 = prime_factorization(number1)
prime_fac_2 = prime_factorization(number2) prime_fac_2 = prime_factorization(number2)
elif number1 == 1 or number2 == 1: elif number1 == 1 or number2 == 1:
prime_fac_1 = [] prime_fac_1 = []
prime_fac_2 = [] prime_fac_2 = []
ans = max(number1, number2) ans = max(number1, number2)
@ -398,11 +385,8 @@ def kg_v(number1, number2):
# iterates through primeFac1 # iterates through primeFac1
for n in prime_fac_1: for n in prime_fac_1:
if n not in done: if n not in done:
if n in prime_fac_2: if n in prime_fac_2:
count1 = prime_fac_1.count(n) count1 = prime_fac_1.count(n)
count2 = prime_fac_2.count(n) count2 = prime_fac_2.count(n)
@ -410,7 +394,6 @@ def kg_v(number1, number2):
ans *= n ans *= n
else: else:
count1 = prime_fac_1.count(n) count1 = prime_fac_1.count(n)
for _ in range(count1): for _ in range(count1):
@ -420,9 +403,7 @@ def kg_v(number1, number2):
# iterates through primeFac2 # iterates through primeFac2
for n in prime_fac_2: for n in prime_fac_2:
if n not in done: if n not in done:
count2 = prime_fac_2.count(n) count2 = prime_fac_2.count(n)
for _ in range(count2): for _ in range(count2):
@ -455,7 +436,6 @@ def get_prime(n):
ans = 2 # this variable holds the answer ans = 2 # this variable holds the answer
while index < n: while index < n:
index += 1 index += 1
ans += 1 # counts to the next number ans += 1 # counts to the next number
@ -499,7 +479,6 @@ def get_primes_between(p_number_1, p_number_2):
number += 1 number += 1
while number < p_number_2: while number < p_number_2:
ans.append(number) ans.append(number)
number += 1 number += 1
@ -534,7 +513,6 @@ def get_divisors(n):
ans = [] # will be returned. ans = [] # will be returned.
for divisor in range(1, n + 1): for divisor in range(1, n + 1):
if n % divisor == 0: if n % divisor == 0:
ans.append(divisor) ans.append(divisor)
@ -638,7 +616,6 @@ def fib(n):
ans = 1 # this will be return ans = 1 # this will be return
for _ in range(n - 1): for _ in range(n - 1):
tmp = ans tmp = ans
ans += fib1 ans += fib1
fib1 = tmp fib1 = tmp

View File

@ -25,7 +25,6 @@ def sieve(n: int) -> list[int]:
while low <= n: while low <= n:
temp = [True] * (high - low + 1) temp = [True] * (high - low + 1)
for each in in_prime: for each in in_prime:
t = math.floor(low / each) * each t = math.floor(low / each) * each
if t < low: if t < low:
t += each t += each

View File

@ -43,7 +43,6 @@ def two_pointer(nums: list[int], target: int) -> list[int]:
j = len(nums) - 1 j = len(nums) - 1
while i < j: while i < j:
if nums[i] + nums[j] == target: if nums[i] + nums[j] == target:
return [i, j] return [i, j]
elif nums[i] + nums[j] < target: elif nums[i] + nums[j] < target:

View File

@ -3,7 +3,6 @@ import datetime
def zeller(date_input: str) -> str: def zeller(date_input: str) -> str:
""" """
Zellers Congruence Algorithm Zellers Congruence Algorithm
Find the day of the week for nearly any Gregorian or Julian calendar date Find the day of the week for nearly any Gregorian or Julian calendar date

View File

@ -59,7 +59,6 @@ def largest_square_area_in_matrix_top_down_approch(
""" """
def update_area_of_max_square(row: int, col: int) -> int: def update_area_of_max_square(row: int, col: int) -> int:
# BASE CASE # BASE CASE
if row >= rows or col >= cols: if row >= rows or col >= cols:
return 0 return 0
@ -138,7 +137,6 @@ def largest_square_area_in_matrix_bottom_up(
largest_square_area = 0 largest_square_area = 0
for row in range(rows - 1, -1, -1): for row in range(rows - 1, -1, -1):
for col in range(cols - 1, -1, -1): for col in range(cols - 1, -1, -1):
right = dp_array[row][col + 1] right = dp_array[row][col + 1]
diagonal = dp_array[row + 1][col + 1] diagonal = dp_array[row + 1][col + 1]
bottom = dp_array[row + 1][col] bottom = dp_array[row + 1][col]
@ -169,7 +167,6 @@ def largest_square_area_in_matrix_bottom_up_space_optimization(
largest_square_area = 0 largest_square_area = 0
for row in range(rows - 1, -1, -1): for row in range(rows - 1, -1, -1):
for col in range(cols - 1, -1, -1): for col in range(cols - 1, -1, -1):
right = current_row[col + 1] right = current_row[col + 1]
diagonal = next_row[col + 1] diagonal = next_row[col + 1]
bottom = next_row[col] bottom = next_row[col]

View File

@ -25,7 +25,6 @@ def print_max_activities(start: list[int], finish: list[int]) -> None:
# Consider rest of the activities # Consider rest of the activities
for j in range(n): for j in range(n):
# If this activity has start time greater than # If this activity has start time greater than
# or equal to the finish time of previously # or equal to the finish time of previously
# selected activity, then select it # selected activity, then select it

View File

@ -15,14 +15,12 @@ brackets and returns true if S is nested and false otherwise.
def is_balanced(s): def is_balanced(s):
stack = [] stack = []
open_brackets = set({"(", "[", "{"}) open_brackets = set({"(", "[", "{"})
closed_brackets = set({")", "]", "}"}) closed_brackets = set({")", "]", "}"})
open_to_closed = dict({"{": "}", "[": "]", "(": ")"}) open_to_closed = dict({"{": "}", "[": "]", "(": ")"})
for i in range(len(s)): for i in range(len(s)):
if s[i] in open_brackets: if s[i] in open_brackets:
stack.append(s[i]) stack.append(s[i])

View File

@ -26,7 +26,6 @@ Thus the weights for each column are as follows:
def procentual_proximity( def procentual_proximity(
source_data: list[list[float]], weights: list[int] source_data: list[list[float]], weights: list[int]
) -> list[list[float]]: ) -> list[list[float]]:
""" """
weights - int list weights - int list
possible values - 0 / 1 possible values - 0 / 1

View File

@ -54,7 +54,6 @@ def function(expansion, s0, s1, key, message):
if __name__ == "__main__": if __name__ == "__main__":
key = input("Enter 10 bit key: ") key = input("Enter 10 bit key: ")
message = input("Enter 8 bit message: ") message = input("Enter 8 bit message: ")

View File

@ -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]: def casimir_force(force: float, area: float, distance: float) -> dict[str, float]:
""" """
Input Parameters Input Parameters
---------------- ----------------

View File

@ -34,7 +34,6 @@ def hubble_parameter(
dark_energy: float, dark_energy: float,
redshift: float, redshift: float,
) -> float: ) -> float:
""" """
Input Parameters Input Parameters
---------------- ----------------

View File

@ -28,7 +28,6 @@ GRAVITATIONAL_CONSTANT = 6.6743e-11 # unit of G : m^3 * kg^-1 * s^-2
def gravitational_law( def gravitational_law(
force: float, mass_1: float, mass_2: float, distance: float force: float, mass_1: float, mass_2: float, distance: float
) -> dict[str, float]: ) -> dict[str, float]:
""" """
Input Parameters Input Parameters
---------------- ----------------

View File

@ -32,12 +32,10 @@ def solution(n: int = 998001) -> int:
# fetches the next number # fetches the next number
for number in range(n - 1, 9999, -1): for number in range(n - 1, 9999, -1):
str_number = str(number) str_number = str(number)
# checks whether 'str_number' is a palindrome. # checks whether 'str_number' is a palindrome.
if str_number == str_number[::-1]: if str_number == str_number[::-1]:
divisor = 999 divisor = 999
# if 'number' is a product of two 3-digit numbers # if 'number' is a product of two 3-digit numbers

View File

@ -111,7 +111,6 @@ def solution(chain_length: int = 60, number_limit: int = 1000000) -> int:
chain_sets_lengths: dict[int, int] = {} chain_sets_lengths: dict[int, int] = {}
for start_chain_element in range(1, number_limit): for start_chain_element in range(1, number_limit):
# The temporary set will contain the elements of the chain # The temporary set will contain the elements of the chain
chain_set = set() chain_set = set()
chain_set_length = 0 chain_set_length = 0

View File

@ -138,5 +138,4 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
if __name__ == "__main__": if __name__ == "__main__":
print(f"{solution() = }") print(f"{solution() = }")

View File

@ -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: def next_number(number: int) -> int:
""" """
Returns the next number of the chain by adding the square of each digit Returns the next number of the chain by adding the square of each digit
to form a new number. to form a new number.
@ -31,7 +30,6 @@ def next_number(number: int) -> int:
sum_of_digits_squared = 0 sum_of_digits_squared = 0
while number: while number:
# Increased Speed Slightly by checking every 5 digits together. # Increased Speed Slightly by checking every 5 digits together.
sum_of_digits_squared += DIGITS_SQUARED[number % 100000] sum_of_digits_squared += DIGITS_SQUARED[number % 100000]
number //= 100000 number //= 100000

View File

@ -72,7 +72,6 @@ def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts
counter = number_of_qubits counter = number_of_qubits
for i in range(counter): for i in range(counter):
quantum_circuit.h(number_of_qubits - i - 1) quantum_circuit.h(number_of_qubits - i - 1)
counter -= 1 counter -= 1
for j in range(counter): for j in range(counter):

View File

@ -18,7 +18,6 @@ from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, exec
def quantum_teleportation( def quantum_teleportation(
theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2
) -> qiskit.result.counts.Counts: ) -> qiskit.result.counts.Counts:
""" """
# >>> quantum_teleportation() # >>> quantum_teleportation()
#{'00': 500, '11': 500} # ideally #{'00': 500, '11': 500} # ideally

View File

@ -37,7 +37,6 @@ def calculate_turn_around_time(
arrival_time.sort() arrival_time.sort()
while no_of_process > finished_process_count: while no_of_process > finished_process_count:
""" """
If the current time is less than the arrival time of If the current time is less than the arrival time of
the process that arrives first among the processes that have not been performed, the process that arrives first among the processes that have not been performed,
@ -94,7 +93,6 @@ def calculate_waiting_time(
if __name__ == "__main__": if __name__ == "__main__":
no_of_process = 5 no_of_process = 5
process_name = ["A", "B", "C", "D", "E"] process_name = ["A", "B", "C", "D", "E"]
arrival_time = [1, 2, 3, 4, 5] arrival_time = [1, 2, 3, 4, 5]

View File

@ -261,7 +261,6 @@ def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None
def binary_search_by_recursion( def binary_search_by_recursion(
sorted_collection: list[int], item: int, left: int, right: int sorted_collection: list[int], item: int, left: int, right: int
) -> int | None: ) -> int | None:
"""Pure implementation of binary search algorithm in Python by recursion """Pure implementation of binary search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be Be careful collection must be ascending sorted, otherwise result will be

View File

@ -49,7 +49,6 @@ def interpolation_search(sorted_collection, item):
def interpolation_search_by_recursion(sorted_collection, item, left, right): def interpolation_search_by_recursion(sorted_collection, item, left, right):
"""Pure implementation of interpolation search algorithm in Python by recursion """Pure implementation of interpolation search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be Be careful collection must be ascending sorted, otherwise result will be
unpredictable unpredictable

View File

@ -220,7 +220,6 @@ def tabu_search(
while not found: while not found:
i = 0 i = 0
while i < len(best_solution): while i < len(best_solution):
if best_solution[i] != solution[i]: if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i] first_exchange_node = best_solution[i]
second_exchange_node = solution[i] second_exchange_node = solution[i]

View File

@ -103,7 +103,6 @@ def ite_ternary_search(array: list[int], target: int) -> int:
left = two_third + 1 left = two_third + 1
else: else:
left = one_third + 1 left = one_third + 1
right = two_third - 1 right = two_third - 1
else: else:

View File

@ -37,7 +37,6 @@ def comb_sort(data: list) -> list:
completed = False completed = False
while not completed: while not completed:
# Update the gap value for a next comb # Update the gap value for a next comb
gap = int(gap / shrink_factor) gap = int(gap / shrink_factor)
if gap <= 1: if gap <= 1:

View File

@ -30,7 +30,6 @@ def odd_even_sort(input_list: list) -> list:
is_sorted = True is_sorted = True
for i in range(0, len(input_list) - 1, 2): # iterating over all even indices for i in range(0, len(input_list) - 1, 2): # iterating over all even indices
if input_list[i] > input_list[i + 1]: if input_list[i] > input_list[i + 1]:
input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i] input_list[i], input_list[i + 1] = input_list[i + 1], input_list[i]
# swapping if elements not in order # swapping if elements not in order
is_sorted = False is_sorted = False

View File

@ -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 # 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 # find out we are sorted as it does to sort the list with this algorithm
for i in range(0, 10): for i in range(0, 10):
if (i + position) % 2 == 0 and r_send is not None: if (i + position) % 2 == 0 and r_send is not None:
# send your value to your right neighbor # send your value to your right neighbor
process_lock.acquire() process_lock.acquire()

View File

@ -19,7 +19,6 @@ def _in_place_quick_sort(a, start, end):
def _in_place_partition(a, start, end): def _in_place_partition(a, start, end):
count = 0 count = 0
pivot = randint(start, end) pivot = randint(start, end)
temp = a[end] temp = a[end]
@ -27,7 +26,6 @@ def _in_place_partition(a, start, end):
a[pivot] = temp a[pivot] = temp
new_pivot_index = start - 1 new_pivot_index = start - 1
for index in range(start, end): for index in range(start, end):
count += 1 count += 1
if a[index] < a[end]: # check if current val is less than pivot value if a[index] < a[end]: # check if current val is less than pivot value
new_pivot_index = new_pivot_index + 1 new_pivot_index = new_pivot_index + 1

View File

@ -44,7 +44,6 @@ def shell_sort(collection: list) -> list:
# Continue sorting until the gap is 1 # Continue sorting until the gap is 1
while gap > 1: while gap > 1:
# Decrease the gap value # Decrease the gap value
gap = int(gap / shrink) gap = int(gap / shrink)

View File

@ -12,7 +12,6 @@ def stooge_sort(arr):
def stooge(arr, i, h): def stooge(arr, i, h):
if i >= h: if i >= h:
return return

View File

@ -73,7 +73,6 @@ def tim_sort(lst):
def main(): def main():
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
sorted_lst = tim_sort(lst) sorted_lst = tim_sort(lst)
print(sorted_lst) print(sorted_lst)

View File

@ -2,7 +2,6 @@ import re
def dna(dna: str) -> str: def dna(dna: str) -> str:
""" """
https://en.wikipedia.org/wiki/DNA https://en.wikipedia.org/wiki/DNA
Returns the second side of a DNA strand Returns the second side of a DNA strand

View File

@ -35,7 +35,6 @@ def hamming_distance(string1: str, string2: str) -> int:
if __name__ == "__main__": if __name__ == "__main__":
import doctest import doctest
doctest.testmod() doctest.testmod()

View File

@ -44,11 +44,9 @@ def levenshtein_distance(first_word: str, second_word: str) -> int:
previous_row = list(range(len(second_word) + 1)) previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word): for i, c1 in enumerate(first_word):
current_row = [i + 1] current_row = [i + 1]
for j, c2 in enumerate(second_word): for j, c2 in enumerate(second_word):
# Calculate insertions, deletions and substitutions # Calculate insertions, deletions and substitutions
insertions = previous_row[j + 1] + 1 insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1 deletions = current_row[j] + 1

View File

@ -29,7 +29,6 @@ def prefix_function(input_string: str) -> list:
prefix_result = [0] * len(input_string) prefix_result = [0] * len(input_string)
for i in range(1, len(input_string)): for i in range(1, len(input_string)):
# use last results for better performance - dynamic programming # use last results for better performance - dynamic programming
j = prefix_result[i - 1] j = prefix_result[i - 1]
while j > 0 and input_string[i] != input_string[j]: while j > 0 and input_string[i] != input_string[j]:

View File

@ -33,7 +33,6 @@ def text_justification(word: str, max_width: int) -> list:
words = word.split() words = word.split()
def justify(line: list, width: int, max_width: int) -> str: def justify(line: list, width: int, max_width: int) -> str:
overall_spaces_count = max_width - width overall_spaces_count = max_width - width
words_count = len(line) words_count = len(line)
if len(line) == 1: if len(line) == 1:

View File

@ -8,7 +8,6 @@ BASE_URL = "https://ww1.gogoanime2.org"
def search_scraper(anime_name: str) -> list: def search_scraper(anime_name: str) -> list:
"""[summary] """[summary]
Take an url and Take an url and
@ -66,7 +65,6 @@ def search_scraper(anime_name: str) -> list:
def search_anime_episode_list(episode_endpoint: str) -> list: def search_anime_episode_list(episode_endpoint: str) -> list:
"""[summary] """[summary]
Take an url and 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: def get_anime_episode(episode_endpoint: str) -> list:
"""[summary] """[summary]
Get click url and download url from episode url Get click url and download url from episode url
@ -153,7 +150,6 @@ def get_anime_episode(episode_endpoint: str) -> list:
if __name__ == "__main__": if __name__ == "__main__":
anime_name = input("Enter anime name: ").strip() anime_name = input("Enter anime name: ").strip()
anime_list = search_scraper(anime_name) anime_list = search_scraper(anime_name)
print("\n") print("\n")
@ -161,9 +157,8 @@ if __name__ == "__main__":
if len(anime_list) == 0: if len(anime_list) == 0:
print("No anime found with this name") print("No anime found with this name")
else: else:
print(f"Found {len(anime_list)} results: ") 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"] anime_title = anime["title"]
print(f"{i+1}. {anime_title}") print(f"{i+1}. {anime_title}")
@ -176,7 +171,7 @@ if __name__ == "__main__":
print("No episode found for this anime") print("No episode found for this anime")
else: else:
print(f"Found {len(episode_list)} results: ") 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']}") print(f"{i+1}. {episode['title']}")
episode_choice = int(input("\nChoose an episode by serial no: ").strip()) episode_choice = int(input("\nChoose an episode by serial no: ").strip())

View File

@ -37,7 +37,6 @@ def fetch_pharmacy_and_price_list(drug_name: str, zip_code: str) -> list | None:
""" """
try: try:
# Has user provided both inputs? # Has user provided both inputs?
if not drug_name or not zip_code: if not drug_name or not zip_code:
return None 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"}) grid_list = soup.find_all("div", {"class": "grid-x pharmCard"})
if grid_list and len(grid_list) > 0: if grid_list and len(grid_list) > 0:
for grid in grid_list: for grid in grid_list:
# Get the pharmacy price. # Get the pharmacy price.
pharmacy_name = grid.find("p", {"class": "list-title"}).text 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__": if __name__ == "__main__":
# Enter a drug name and a zip code # Enter a drug name and a zip code
drug_name = input("Enter drug name: ").strip() drug_name = input("Enter drug name: ").strip()
zip_code = input("Enter zip code: ").strip() zip_code = input("Enter zip code: ").strip()
@ -89,10 +86,8 @@ if __name__ == "__main__":
) )
if pharmacy_price_list: if pharmacy_price_list:
print(f"\nSearch results for {drug_name} at location {zip_code}:") print(f"\nSearch results for {drug_name} at location {zip_code}:")
for pharmacy_price in pharmacy_price_list: for pharmacy_price in pharmacy_price_list:
name = pharmacy_price["pharmacy_name"] name = pharmacy_price["pharmacy_name"]
price = pharmacy_price["price"] price = pharmacy_price["price"]

View File

@ -10,7 +10,6 @@ access_secret = ""
def get_all_tweets(screen_name: str) -> None: def get_all_tweets(screen_name: str) -> None:
# authorize twitter, initialize tweepy # authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret) auth.set_access_token(access_key, access_secret)