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
- repo: https://github.com/psf/black
rev: 22.12.0
rev: 23.1.0
hooks:
- id: black
@ -26,6 +26,16 @@ repos:
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:

View File

@ -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)}")

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
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

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----------------
# This function find the inverses of a i.e., a^(-1)
def invert_modulo(a: int, n: int) -> int:
"""

View File

@ -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]

View File

@ -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"

View File

@ -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:

View File

@ -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))

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

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

View File

@ -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:

View File

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

View File

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

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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:

View File

@ -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

View File

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

View File

@ -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()

View File

@ -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))

View File

@ -92,7 +92,6 @@ class Stack(Generic[T]):
# Code execution starts here
if __name__ == "__main__":
# Start with the empty 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):
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]:

View File

@ -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)

View File

@ -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

View File

@ -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.

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

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

View File

@ -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=" ")

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

View File

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

View File

@ -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):

View File

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

View File

@ -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)

View File

@ -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, :]

View File

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

View File

@ -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"

View File

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

View File

@ -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

View File

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

View File

@ -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",

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:
"""
Isolates the decimal part of a number.
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):
if n == 0:
return 1

View File

@ -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"

View File

@ -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

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):
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:

View File

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

View File

@ -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)

View File

@ -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))

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):
a = x0 # set the initial guess
steps = [a]
error = abs(f(a))

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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

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:
# 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]

View File

@ -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

View File

@ -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])

View File

@ -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

View File

@ -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: ")

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]:
"""
Input Parameters
----------------

View File

@ -34,7 +34,6 @@ def hubble_parameter(
dark_energy: float,
redshift: float,
) -> float:
"""
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(
force: float, mass_1: float, mass_2: float, distance: float
) -> dict[str, float]:
"""
Input Parameters
----------------

View File

@ -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

View File

@ -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

View File

@ -138,5 +138,4 @@ def solution(roman_numerals_filename: str = "/p089_roman.txt") -> int:
if __name__ == "__main__":
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:
"""
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

View File

@ -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):

View File

@ -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

View File

@ -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]

View File

@ -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

View File

@ -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

View File

@ -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]

View File

@ -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:

View File

@ -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:

View File

@ -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

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
# 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()

View File

@ -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

View File

@ -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)

View File

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

View File

@ -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)

View File

@ -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

View File

@ -35,7 +35,6 @@ def hamming_distance(string1: str, string2: str) -> int:
if __name__ == "__main__":
import doctest
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))
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

View File

@ -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]:

View File

@ -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:

View File

@ -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())

View File

@ -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"]

View File

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