The black formatter is no longer beta (#5960)

* The black formatter is no longer beta

* pre-commit autoupdate

* pre-commit autoupdate

* Remove project_euler/problem_145 which is killing our CI tests

* updating DIRECTORY.md

Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
This commit is contained in:
Christian Clauss 2022-01-30 20:29:54 +01:00 committed by GitHub
parent c15a4d5af6
commit 24d3cf8244
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
81 changed files with 139 additions and 228 deletions

View File

@ -1,6 +1,6 @@
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0 rev: v4.1.0
hooks: hooks:
- id: check-executables-have-shebangs - id: check-executables-have-shebangs
- id: check-yaml - id: check-yaml
@ -14,26 +14,26 @@ repos:
- id: requirements-txt-fixer - id: requirements-txt-fixer
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 21.4b0 rev: 22.1.0
hooks: hooks:
- id: black - id: black
- repo: https://github.com/PyCQA/isort - repo: https://github.com/PyCQA/isort
rev: 5.8.0 rev: 5.10.1
hooks: hooks:
- id: isort - id: isort
args: args:
- --profile=black - --profile=black
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v2.29.0 rev: v2.31.0
hooks: hooks:
- id: pyupgrade - id: pyupgrade
args: args:
- --py39-plus - --py39-plus
- repo: https://gitlab.com/pycqa/flake8 - repo: https://gitlab.com/pycqa/flake8
rev: 3.9.1 rev: 3.9.2
hooks: hooks:
- id: flake8 - id: flake8
args: args:
@ -42,7 +42,7 @@ repos:
- --max-line-length=88 - --max-line-length=88
- repo: https://github.com/pre-commit/mirrors-mypy - repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910 rev: v0.931
hooks: hooks:
- id: mypy - id: mypy
args: args:
@ -51,11 +51,11 @@ repos:
- --non-interactive - --non-interactive
- repo: https://github.com/codespell-project/codespell - repo: https://github.com/codespell-project/codespell
rev: v2.0.0 rev: v2.1.0
hooks: hooks:
- id: codespell - id: codespell
args: args:
- --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,tim - --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,sur,tim
- --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt" - --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt"
exclude: | exclude: |
(?x)^( (?x)^(

View File

@ -856,8 +856,6 @@
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144 * Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 145
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_145/sol1.py)
* Problem 173 * Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py) * [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174 * Problem 174

View File

@ -32,7 +32,7 @@ def bisection(function: Callable[[float], float], a: float, b: float) -> float:
raise ValueError("could not find root in given interval.") raise ValueError("could not find root in given interval.")
else: else:
mid: float = start + (end - start) / 2.0 mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7 while abs(start - mid) > 10**-7: # until precisely equals to 10^-7
if function(mid) == 0: if function(mid) == 0:
return mid return mid
elif function(mid) * function(start) < 0: elif function(mid) * function(start) < 0:
@ -44,7 +44,7 @@ def bisection(function: Callable[[float], float], a: float, b: float) -> float:
def f(x: float) -> float: def f(x: float) -> float:
return x ** 3 - 2 * x - 5 return x**3 - 2 * x - 5
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -23,7 +23,7 @@ def polar_force(
def in_static_equilibrium( def in_static_equilibrium(
forces: ndarray, location: ndarray, eps: float = 10 ** -1 forces: ndarray, location: ndarray, eps: float = 10**-1
) -> bool: ) -> bool:
""" """
Check if a system is in equilibrium. Check if a system is in equilibrium.

View File

@ -35,7 +35,7 @@ def intersection(function: Callable[[float], float], x0: float, x1: float) -> fl
x_n2: float = x_n1 - ( x_n2: float = x_n1 - (
function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n))
) )
if abs(x_n2 - x_n1) < 10 ** -5: if abs(x_n2 - x_n1) < 10**-5:
return x_n2 return x_n2
x_n = x_n1 x_n = x_n1
x_n1 = x_n2 x_n1 = x_n2

View File

@ -37,17 +37,17 @@ def newton(
next_guess = prev_guess - function(prev_guess) / derivative(prev_guess) next_guess = prev_guess - function(prev_guess) / derivative(prev_guess)
except ZeroDivisionError: except ZeroDivisionError:
raise ZeroDivisionError("Could not find root") from None raise ZeroDivisionError("Could not find root") from None
if abs(prev_guess - next_guess) < 10 ** -5: if abs(prev_guess - next_guess) < 10**-5:
return next_guess return next_guess
prev_guess = next_guess prev_guess = next_guess
def f(x: float) -> float: def f(x: float) -> float:
return (x ** 3) - (2 * x) - 5 return (x**3) - (2 * x) - 5
def f1(x: float) -> float: def f1(x: float) -> float:
return 3 * (x ** 2) - 2 return 3 * (x**2) - 2
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -11,7 +11,7 @@ from sympy import diff
def newton_raphson( def newton_raphson(
func: str, a: float | Decimal, precision: float = 10 ** -10 func: str, a: float | Decimal, precision: float = 10**-10
) -> float: ) -> float:
"""Finds root from the point 'a' onwards by Newton-Raphson method """Finds root from the point 'a' onwards by Newton-Raphson method
>>> newton_raphson("sin(x)", 2) >>> newton_raphson("sin(x)", 2)

View File

@ -73,7 +73,7 @@ def miller_rabin(n: int, allow_probable: bool = False) -> bool:
for prime in plist: for prime in plist:
pr = False pr = False
for r in range(s): for r in range(s):
m = pow(prime, d * 2 ** r, n) m = pow(prime, d * 2**r, n)
# see article for analysis explanation for m # see article for analysis explanation for m
if (r == 0 and m == 1) or ((m + 1) % n == 0): if (r == 0 and m == 1) or ((m + 1) % n == 0):
pr = True pr = True

View File

@ -21,7 +21,7 @@ def rabinMiller(num: int) -> bool:
return False return False
else: else:
i = i + 1 i = i + 1
v = (v ** 2) % num v = (v**2) % num
return True return True

View File

@ -29,8 +29,8 @@ def get_text_from_blocks(
block_message: list[str] = [] block_message: list[str] = []
for i in range(block_size - 1, -1, -1): for i in range(block_size - 1, -1, -1):
if len(message) + i < message_length: if len(message) + i < message_length:
ascii_number = block_int // (BYTE_SIZE ** i) ascii_number = block_int // (BYTE_SIZE**i)
block_int = block_int % (BYTE_SIZE ** i) block_int = block_int % (BYTE_SIZE**i)
block_message.insert(0, chr(ascii_number)) block_message.insert(0, chr(ascii_number))
message.extend(block_message) message.extend(block_message)
return "".join(message) return "".join(message)

View File

@ -40,7 +40,7 @@ def rsafactor(d: int, e: int, N: int) -> list[int]:
while True: while True:
if t % 2 == 0: if t % 2 == 0:
t = t // 2 t = t // 2
x = (g ** t) % N x = (g**t) % N
y = math.gcd(x - 1, N) y = math.gcd(x - 1, N)
if x > 1 and y > 1: if x > 1 and y > 1:
p = y p = y

View File

@ -39,8 +39,8 @@ class Harris_Corner:
color_img = img.copy() color_img = img.copy()
color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB)
dy, dx = np.gradient(img) dy, dx = np.gradient(img)
ixx = dx ** 2 ixx = dx**2
iyy = dy ** 2 iyy = dy**2
ixy = dx * dy ixy = dx * dy
k = 0.04 k = 0.04
offset = self.window_size // 2 offset = self.window_size // 2
@ -56,9 +56,9 @@ class Harris_Corner:
y - offset : y + offset + 1, x - offset : x + offset + 1 y - offset : y + offset + 1, x - offset : x + offset + 1
].sum() ].sum()
det = (wxx * wyy) - (wxy ** 2) det = (wxx * wyy) - (wxy**2)
trace = wxx + wyy trace = wxx + wyy
r = det - k * (trace ** 2) r = det - k * (trace**2)
# Can change the value # Can change the value
if r > 0.5: if r > 0.5:
corner_list.append([x, y, r]) corner_list.append([x, y, r])

View File

@ -49,7 +49,7 @@ def gabor_filter_kernel(
# fill kernel # fill kernel
gabor[y, x] = np.exp( gabor[y, x] = np.exp(
-(_x ** 2 + gamma ** 2 * _y ** 2) / (2 * sigma ** 2) -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)
) * np.cos(2 * np.pi * _x / lambd + psi) ) * np.cos(2 * np.pi * _x / lambd + psi)
return gabor return gabor

View File

@ -203,7 +203,7 @@ class IndexCalculation:
https://www.indexdatabase.de/db/i-single.php?id=391 https://www.indexdatabase.de/db/i-single.php?id=391
:return: index :return: index
""" """
return self.nir * (self.red / (self.green ** 2)) return self.nir * (self.red / (self.green**2))
def GLI(self): def GLI(self):
""" """
@ -295,7 +295,7 @@ class IndexCalculation:
""" """
return a * ( return a * (
(self.nir - a * self.red - b) (self.nir - a * self.red - b)
/ (a * self.nir + self.red - a * b + X * (1 + a ** 2)) / (a * self.nir + self.red - a * b + X * (1 + a**2))
) )
def BWDRVI(self): def BWDRVI(self):
@ -363,7 +363,7 @@ class IndexCalculation:
https://www.indexdatabase.de/db/i-single.php?id=25 https://www.indexdatabase.de/db/i-single.php?id=25
:return: index :return: index
""" """
n = (2 * (self.nir ** 2 - self.red ** 2) + 1.5 * self.nir + 0.5 * self.red) / ( n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
self.nir + self.red + 0.5 self.nir + self.red + 0.5
) )
return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red)

View File

@ -53,12 +53,12 @@ def carrier_concentration(
elif electron_conc == 0: elif electron_conc == 0:
return ( return (
"electron_conc", "electron_conc",
intrinsic_conc ** 2 / hole_conc, intrinsic_conc**2 / hole_conc,
) )
elif hole_conc == 0: elif hole_conc == 0:
return ( return (
"hole_conc", "hole_conc",
intrinsic_conc ** 2 / electron_conc, intrinsic_conc**2 / electron_conc,
) )
elif intrinsic_conc == 0: elif intrinsic_conc == 0:
return ( return (

View File

@ -66,13 +66,13 @@ def couloumbs_law(
if distance < 0: if distance < 0:
raise ValueError("Distance cannot be negative") raise ValueError("Distance cannot be negative")
if force == 0: if force == 0:
force = COULOMBS_CONSTANT * charge_product / (distance ** 2) force = COULOMBS_CONSTANT * charge_product / (distance**2)
return {"force": force} return {"force": force}
elif charge1 == 0: elif charge1 == 0:
charge1 = abs(force) * (distance ** 2) / (COULOMBS_CONSTANT * charge2) charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2)
return {"charge1": charge1} return {"charge1": charge1}
elif charge2 == 0: elif charge2 == 0:
charge2 = abs(force) * (distance ** 2) / (COULOMBS_CONSTANT * charge1) charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1)
return {"charge2": charge2} return {"charge2": charge2}
elif distance == 0: elif distance == 0:
distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5 distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5

View File

@ -40,7 +40,7 @@ class BezierCurve:
for i in range(len(self.list_of_points)): for i in range(len(self.list_of_points)):
# basis function for each i # basis function for each i
output_values.append( output_values.append(
comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t ** i) comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t**i)
) )
# the basis must sum up to 1 for it to produce a valid Bezier curve. # the basis must sum up to 1 for it to produce a valid Bezier curve.
assert round(sum(output_values), 5) == 1 assert round(sum(output_values), 5) == 1

View File

@ -68,7 +68,7 @@ class Node:
if HEURISTIC == 1: if HEURISTIC == 1:
return abs(dx) + abs(dy) return abs(dx) + abs(dy)
else: else:
return sqrt(dy ** 2 + dx ** 2) return sqrt(dy**2 + dx**2)
def __lt__(self, other: Node) -> bool: def __lt__(self, other: Node) -> bool:
return self.f_cost < other.f_cost return self.f_cost < other.f_cost

View File

@ -63,8 +63,8 @@ def pull():
params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3 params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3
# Choosing Chaotic Data # Choosing Chaotic Data
X = int(buffer_space[(key + 2) % m] * (10 ** 10)) X = int(buffer_space[(key + 2) % m] * (10**10))
Y = int(buffer_space[(key - 2) % m] * (10 ** 10)) Y = int(buffer_space[(key - 2) % m] * (10**10))
# Machine Time # Machine Time
machine_time += 1 machine_time += 1

View File

@ -78,7 +78,7 @@ def emitterConverter(sizePar, data):
>>> emitterConverter(4, "101010111111") >>> emitterConverter(4, "101010111111")
['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']
""" """
if sizePar + len(data) <= 2 ** sizePar - (len(data) - 1): if sizePar + len(data) <= 2**sizePar - (len(data) - 1):
print("ERROR - size of parity don't match with size of data") print("ERROR - size of parity don't match with size of data")
exit(0) exit(0)

View File

@ -94,7 +94,7 @@ def not32(i):
def sum32(a, b): def sum32(a, b):
return (a + b) % 2 ** 32 return (a + b) % 2**32
def leftrot32(i, s): def leftrot32(i, s):
@ -114,7 +114,7 @@ def md5me(testString):
bs += format(ord(i), "08b") bs += format(ord(i), "08b")
bs = pad(bs) bs = pad(bs)
tvals = [int(2 ** 32 * abs(math.sin(i + 1))) for i in range(64)] tvals = [int(2**32 * abs(math.sin(i + 1))) for i in range(64)]
a0 = 0x67452301 a0 = 0x67452301
b0 = 0xEFCDAB89 b0 = 0xEFCDAB89
@ -211,7 +211,7 @@ def md5me(testString):
dtemp = D dtemp = D
D = C D = C
C = B C = B
B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2 ** 32, s[i])) B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2**32, s[i]))
A = dtemp A = dtemp
a0 = sum32(a0, A) a0 = sum32(a0, A)
b0 = sum32(b0, B) b0 = sum32(b0, B)

View File

@ -172,7 +172,7 @@ class Vector:
""" """
if len(self.__components) == 0: if len(self.__components) == 0:
raise Exception("Vector is empty") raise Exception("Vector is empty")
squares = [c ** 2 for c in self.__components] squares = [c**2 for c in self.__components]
return math.sqrt(sum(squares)) return math.sqrt(sum(squares))
def angle(self, other: Vector, deg: bool = False) -> float: def angle(self, other: Vector, deg: bool = False) -> float:

View File

@ -112,7 +112,7 @@ def compute_heterogeneity(data, k, centroids, cluster_assignment):
distances = pairwise_distances( distances = pairwise_distances(
member_data_points, [centroids[i]], metric="euclidean" member_data_points, [centroids[i]], metric="euclidean"
) )
squared_distances = distances ** 2 squared_distances = distances**2
heterogeneity += np.sum(squared_distances) heterogeneity += np.sum(squared_distances)
return heterogeneity return heterogeneity

View File

@ -25,7 +25,7 @@ def weighted_matrix(point: np.mat, training_data_x: np.mat, bandwidth: float) ->
# calculating weights for all training examples [x(i)'s] # calculating weights for all training examples [x(i)'s]
for j in range(m): for j in range(m):
diff = point - training_data_x[j] diff = point - training_data_x[j]
weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth ** 2)) weights[j, j] = np.exp(diff * diff.T / (-2.0 * bandwidth**2))
return weights return weights

View File

@ -345,15 +345,15 @@ class SmoSVM:
ol = ( ol = (
l1 * f1 l1 * f1
+ L * f2 + L * f2
+ 1 / 2 * l1 ** 2 * K(i1, i1) + 1 / 2 * l1**2 * K(i1, i1)
+ 1 / 2 * L ** 2 * K(i2, i2) + 1 / 2 * L**2 * K(i2, i2)
+ s * L * l1 * K(i1, i2) + s * L * l1 * K(i1, i2)
) )
oh = ( oh = (
h1 * f1 h1 * f1
+ H * f2 + H * f2
+ 1 / 2 * h1 ** 2 * K(i1, i1) + 1 / 2 * h1**2 * K(i1, i1)
+ 1 / 2 * H ** 2 * K(i2, i2) + 1 / 2 * H**2 * K(i2, i2)
+ s * H * h1 * K(i1, i2) + s * H * h1 * K(i1, i2)
) )
""" """

View File

@ -19,7 +19,7 @@ def surface_area_cube(side_length: float) -> float:
""" """
if side_length < 0: if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values") raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length ** 2 return 6 * side_length**2
def surface_area_sphere(radius: float) -> float: def surface_area_sphere(radius: float) -> float:
@ -39,7 +39,7 @@ def surface_area_sphere(radius: float) -> float:
""" """
if radius < 0: if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values") raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius ** 2 return 4 * pi * radius**2
def surface_area_hemisphere(radius: float) -> float: def surface_area_hemisphere(radius: float) -> float:
@ -62,7 +62,7 @@ def surface_area_hemisphere(radius: float) -> float:
""" """
if radius < 0: if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values") raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius ** 2 return 3 * pi * radius**2
def surface_area_cone(radius: float, height: float) -> float: def surface_area_cone(radius: float, height: float) -> float:
@ -90,7 +90,7 @@ def surface_area_cone(radius: float, height: float) -> float:
""" """
if radius < 0 or height < 0: if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values") raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height ** 2 + radius ** 2) ** 0.5) return pi * radius * (radius + (height**2 + radius**2) ** 0.5)
def surface_area_cylinder(radius: float, height: float) -> float: def surface_area_cylinder(radius: float, height: float) -> float:
@ -158,7 +158,7 @@ def area_square(side_length: float) -> float:
""" """
if side_length < 0: if side_length < 0:
raise ValueError("area_square() only accepts non-negative values") raise ValueError("area_square() only accepts non-negative values")
return side_length ** 2 return side_length**2
def area_triangle(base: float, height: float) -> float: def area_triangle(base: float, height: float) -> float:
@ -307,7 +307,7 @@ def area_circle(radius: float) -> float:
""" """
if radius < 0: if radius < 0:
raise ValueError("area_circle() only accepts non-negative values") raise ValueError("area_circle() only accepts non-negative values")
return pi * radius ** 2 return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float: def area_ellipse(radius_x: float, radius_y: float) -> float:

View File

@ -50,7 +50,7 @@ def trapezoidal_area(
if __name__ == "__main__": if __name__ == "__main__":
def f(x): def f(x):
return x ** 3 + x ** 2 return x**3 + x**2
print("f(x) = x^3 + x^2") print("f(x) = x^3 + x^2")
print("The area between the curve, x = -5, x = 5 and the x axis is:") print("The area between the curve, x = -5, x = 5 and the x axis is:")

View File

@ -36,7 +36,7 @@ def armstrong_number(n: int) -> bool:
temp = n temp = n
while temp > 0: while temp > 0:
rem = temp % 10 rem = temp % 10
sum += rem ** number_of_digits sum += rem**number_of_digits
temp //= 10 temp //= 10
return n == sum return n == sum
@ -63,7 +63,7 @@ def pluperfect_number(n: int) -> bool:
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))):
sum += cnt * i ** digit_total sum += cnt * i**digit_total
return n == sum return n == sum

View File

@ -81,14 +81,14 @@ def sum_of_divisors(n: int) -> int:
temp += 1 temp += 1
n = int(n / 2) n = int(n / 2)
if temp > 1: if temp > 1:
s *= (2 ** temp - 1) / (2 - 1) s *= (2**temp - 1) / (2 - 1)
for i in range(3, int(math.sqrt(n)) + 1, 2): for i in range(3, int(math.sqrt(n)) + 1, 2):
temp = 1 temp = 1
while n % i == 0: while n % i == 0:
temp += 1 temp += 1
n = int(n / i) n = int(n / i)
if temp > 1: if temp > 1:
s *= (i ** temp - 1) / (i - 1) s *= (i**temp - 1) / (i - 1)
return int(s) return int(s)

View File

@ -24,7 +24,7 @@ def binomial_distribution(successes: int, trials: int, prob: float) -> float:
raise ValueError("the function is defined for non-negative integers") raise ValueError("the function is defined for non-negative integers")
if not 0 < prob < 1: if not 0 < prob < 1:
raise ValueError("prob has to be in range of 1 - 0") raise ValueError("prob has to be in range of 1 - 0")
probability = (prob ** successes) * ((1 - prob) ** (trials - successes)) probability = (prob**successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)! # Calculate the binomial coefficient: n! / k!(n-k)!
coefficient = float(factorial(trials)) coefficient = float(factorial(trials))
coefficient /= factorial(successes) * factorial(trials - successes) coefficient /= factorial(successes) * factorial(trials - successes)

View File

@ -159,7 +159,7 @@ def fib_binet(n: int) -> list[int]:
raise Exception("n is too large") raise Exception("n is too large")
sqrt_5 = sqrt(5) sqrt_5 = sqrt(5)
phi = (1 + sqrt_5) / 2 phi = (1 + sqrt_5) / 2
return [round(phi ** i / sqrt_5) for i in range(n + 1)] return [round(phi**i / sqrt_5) for i in range(n + 1)]
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -52,7 +52,7 @@ def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int:
>>> gaussian(2523, mu=234234, sigma=3425) >>> gaussian(2523, mu=234234, sigma=3425)
0.0 0.0
""" """
return 1 / sqrt(2 * pi * sigma ** 2) * exp(-((x - mu) ** 2) / (2 * sigma ** 2)) return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2))
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -14,8 +14,8 @@ def karatsuba(a, b):
m1 = max(len(str(a)), len(str(b))) m1 = max(len(str(a)), len(str(b)))
m2 = m1 // 2 m2 = m1 // 2
a1, a2 = divmod(a, 10 ** m2) a1, a2 = divmod(a, 10**m2)
b1, b2 = divmod(b, 10 ** m2) b1, b2 = divmod(b, 10**m2)
x = karatsuba(a2, b2) x = karatsuba(a2, b2)
y = karatsuba((a1 + a2), (b1 + b2)) y = karatsuba((a1 + a2), (b1 + b2))

View File

@ -20,7 +20,7 @@ def pi_estimator(iterations: int):
""" """
# 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))
# Our circle has a radius of 1, so a distance # Our circle has a radius of 1, so a distance
# greater than 1 would land outside the circle. # greater than 1 would land outside the circle.
return distance_from_centre <= 1 return distance_from_centre <= 1

View File

@ -56,7 +56,7 @@ def trapezoidal_area(
if __name__ == "__main__": if __name__ == "__main__":
def f(x): def f(x):
return x ** 3 return x**3
print("f(x) = x^3") print("f(x) = x^3")
print("The area between the curve, x = -10, x = 10 and the x axis is:") print("The area between the curve, x = -10, x = 10 and the x axis is:")

View File

@ -58,9 +58,9 @@ def perfect_square_binary_search(n: int) -> bool:
right = n right = n
while left <= right: while left <= right:
mid = (left + right) // 2 mid = (left + right) // 2
if mid ** 2 == n: if mid**2 == n:
return True return True
elif mid ** 2 > n: elif mid**2 > n:
right = mid - 1 right = mid - 1
else: else:
left = mid + 1 left = mid + 1

View File

@ -11,7 +11,7 @@ class Point:
True, if the point lies in the unit circle True, if the point lies in the unit circle
False, otherwise False, otherwise
""" """
return (self.x ** 2 + self.y ** 2) <= 1 return (self.x**2 + self.y**2) <= 1
@classmethod @classmethod
def random_unit_square(cls): def random_unit_square(cls):

View File

@ -12,7 +12,7 @@ def evaluate_poly(poly: Sequence[float], x: float) -> float:
>>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0) >>> evaluate_poly((0.0, 0.0, 5.0, 9.3, 7.0), 10.0)
79800.0 79800.0
""" """
return sum(c * (x ** i) for i, c in enumerate(poly)) return sum(c * (x**i) for i, c in enumerate(poly))
def horner(poly: Sequence[float], x: float) -> float: def horner(poly: Sequence[float], x: float) -> float:

View File

@ -91,7 +91,7 @@ class FFT:
next_ncol = self.C_max_length // 2 next_ncol = self.C_max_length // 2
while next_ncol > 0: while next_ncol > 0:
new_dft = [[] for i in range(next_ncol)] new_dft = [[] for i in range(next_ncol)]
root = self.root ** next_ncol root = self.root**next_ncol
# First half of next step # First half of next step
current_root = 1 current_root = 1

View File

@ -48,4 +48,4 @@ def sieve(n):
return prime return prime
print(sieve(10 ** 6)) print(sieve(10**6))

View File

@ -25,4 +25,4 @@ def sum_of_geometric_progression(
return num_of_terms * first_term return num_of_terms * first_term
# Formula for finding sum of n terms of a GeometricProgression # Formula for finding sum of n terms of a GeometricProgression
return (first_term / (1 - common_ratio)) * (1 - common_ratio ** num_of_terms) return (first_term / (1 - common_ratio)) * (1 - common_ratio**num_of_terms)

View File

@ -159,16 +159,16 @@ class BodySystem:
# Calculation of the distance using Pythagoras's theorem # Calculation of the distance using Pythagoras's theorem
# Extra factor due to the softening technique # Extra factor due to the softening technique
distance = (dif_x ** 2 + dif_y ** 2 + self.softening_factor) ** ( distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** (
1 / 2 1 / 2
) )
# Newton's law of universal gravitation. # Newton's law of universal gravitation.
force_x += ( force_x += (
self.gravitation_constant * body2.mass * dif_x / distance ** 3 self.gravitation_constant * body2.mass * dif_x / distance**3
) )
force_y += ( force_y += (
self.gravitation_constant * body2.mass * dif_y / distance ** 3 self.gravitation_constant * body2.mass * dif_y / distance**3
) )
# Update the body's velocity once all the force components have been added # Update the body's velocity once all the force components have been added

View File

@ -35,9 +35,9 @@ def solution(n: int = 100) -> int:
sum_of_squares = 0 sum_of_squares = 0
sum_of_ints = 0 sum_of_ints = 0
for i in range(1, n + 1): for i in range(1, n + 1):
sum_of_squares += i ** 2 sum_of_squares += i**2
sum_of_ints += i sum_of_ints += i
return sum_of_ints ** 2 - sum_of_squares return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -25,7 +25,7 @@ def isprime(number: int) -> bool:
True True
""" """
for i in range(2, int(number ** 0.5) + 1): for i in range(2, int(number**0.5) + 1):
if number % i == 0: if number % i == 0:
return False return False
return True return True

View File

@ -33,7 +33,7 @@ def solution() -> int:
for b in range(a + 1, 400): for b in range(a + 1, 400):
for c in range(b + 1, 500): for c in range(b + 1, 500):
if (a + b + c) == 1000: if (a + b + c) == 1000:
if (a ** 2) + (b ** 2) == (c ** 2): if (a**2) + (b**2) == (c**2):
return a * b * c return a * b * c
return -1 return -1
@ -54,7 +54,7 @@ def solution_fast() -> int:
for a in range(300): for a in range(300):
for b in range(400): for b in range(400):
c = 1000 - a - b c = 1000 - a - b
if a < b < c and (a ** 2) + (b ** 2) == (c ** 2): if a < b < c and (a**2) + (b**2) == (c**2):
return a * b * c return a * b * c
return -1 return -1

View File

@ -46,7 +46,7 @@ def solution(n: int = 2000000) -> int:
primality_list[0] = 1 primality_list[0] = 1
primality_list[1] = 1 primality_list[1] = 1
for i in range(2, int(n ** 0.5) + 1): for i in range(2, int(n**0.5) + 1):
if primality_list[i] == 0: if primality_list[i] == 0:
for j in range(i * i, n + 1, i): for j in range(i * i, n + 1, i):
primality_list[j] = 1 primality_list[j] = 1

View File

@ -18,7 +18,7 @@ def solution(power: int = 1000) -> int:
>>> solution(15) >>> solution(15)
26 26
""" """
num = 2 ** power num = 2**power
string_num = str(num) string_num = str(num)
list_num = list(string_num) list_num = list(string_num)
sum_of_num = 0 sum_of_num = 0
@ -31,6 +31,6 @@ def solution(power: int = 1000) -> int:
if __name__ == "__main__": if __name__ == "__main__":
power = int(input("Enter the power of 2: ").strip()) power = int(input("Enter the power of 2: ").strip())
print("2 ^ ", power, " = ", 2 ** power) print("2 ^ ", power, " = ", 2**power)
result = solution(power) result = solution(power)
print("Sum of the digits is: ", result) print("Sum of the digits is: ", result)

View File

@ -19,7 +19,7 @@ def solution(power: int = 1000) -> int:
>>> solution(15) >>> solution(15)
26 26
""" """
n = 2 ** power n = 2**power
r = 0 r = 0
while n: while n:
r, n = r + n % 10, n // 10 r, n = r + n % 10, n // 10

View File

@ -30,7 +30,7 @@ def solution(limit=28123):
""" """
sumDivs = [1] * (limit + 1) sumDivs = [1] * (limit + 1)
for i in range(2, int(limit ** 0.5) + 1): for i in range(2, int(limit**0.5) + 1):
sumDivs[i * i] += i sumDivs[i * i] += i
for k in range(i + 1, limit // i + 1): for k in range(i + 1, limit // i + 1):
sumDivs[k * i] += k + i sumDivs[k * i] += k + i

View File

@ -61,7 +61,7 @@ def solution(a_limit: int = 1000, b_limit: int = 1000) -> int:
if is_prime(b): if is_prime(b):
count = 0 count = 0
n = 0 n = 0
while is_prime((n ** 2) + (a * n) + b): while is_prime((n**2) + (a * n) + b):
count += 1 count += 1
n += 1 n += 1
if count > longest[0]: if count > longest[0]:

View File

@ -40,7 +40,7 @@ def solution(n: int = 1001) -> int:
for i in range(1, int(ceil(n / 2.0))): for i in range(1, int(ceil(n / 2.0))):
odd = 2 * i + 1 odd = 2 * i + 1
even = 2 * i even = 2 * i
total = total + 4 * odd ** 2 - 6 * even total = total + 4 * odd**2 - 6 * even
return total return total

View File

@ -41,7 +41,7 @@ def solution(n: int = 100) -> int:
for a in range(2, N): for a in range(2, N):
for b in range(2, N): for b in range(2, N):
currentPow = a ** b # calculates the current power currentPow = a**b # calculates the current power
collectPowers.add(currentPow) # adds the result to the set collectPowers.add(currentPow) # adds the result to the set
return len(collectPowers) return len(collectPowers)

View File

@ -17,7 +17,7 @@ def solution():
""" """
total = 0 total = 0
for i in range(1, 1001): for i in range(1, 1001):
total += i ** i total += i**i
return str(total)[-10:] return str(total)[-10:]

View File

@ -35,7 +35,7 @@ def prime_sieve(limit: int) -> list[int]:
is_prime[1] = False is_prime[1] = False
is_prime[2] = True is_prime[2] = True
for i in range(3, int(limit ** 0.5 + 1), 2): for i in range(3, int(limit**0.5 + 1), 2):
index = i * 2 index = i * 2
while index < limit: while index < limit:
is_prime[index] = False is_prime[index] = False

View File

@ -37,7 +37,7 @@ def prime_sieve(n: int) -> list[int]:
is_prime[1] = False is_prime[1] = False
is_prime[2] = True is_prime[2] = True
for i in range(3, int(n ** 0.5 + 1), 2): for i in range(3, int(n**0.5 + 1), 2):
index = i * 2 index = i * 2
while index < n: while index < n:
is_prime[index] = False is_prime[index] = False

View File

@ -30,7 +30,7 @@ def solution(a: int = 100, b: int = 100) -> int:
# RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of
# BASE raised to the POWER # BASE raised to the POWER
return max( return max(
sum(int(x) for x in str(base ** power)) sum(int(x) for x in str(base**power))
for base in range(a) for base in range(a)
for power in range(b) for power in range(b)
) )

View File

@ -55,7 +55,7 @@ def get_digits(num: int) -> str:
>>> get_digits(123) >>> get_digits(123)
'0166788' '0166788'
""" """
return "".join(sorted(list(str(num ** 3)))) return "".join(sorted(list(str(num**3))))
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -26,7 +26,7 @@ def solution(max_base: int = 10, max_power: int = 22) -> int:
bases = range(1, max_base) bases = range(1, max_base)
powers = range(1, max_power) powers = range(1, max_power)
return sum( return sum(
1 for power in powers for base in bases if len(str(base ** power)) == power 1 for power in powers for base in bases if len(str(base**power)) == power
) )

View File

@ -38,7 +38,7 @@ def continuous_fraction_period(n: int) -> int:
period = 0 period = 0
while integer_part != 2 * ROOT: while integer_part != 2 * ROOT:
numerator = denominator * integer_part - numerator numerator = denominator * integer_part - numerator
denominator = (n - numerator ** 2) / denominator denominator = (n - numerator**2) / denominator
integer_part = int((ROOT + numerator) / denominator) integer_part = int((ROOT + numerator) / denominator)
period += 1 period += 1
return period return period

View File

@ -24,7 +24,7 @@ Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
""" """
def solution(n: int = 10 ** 6) -> int: def solution(n: int = 10**6) -> int:
""" """
Returns solution to problem. Returns solution to problem.
Algorithm: Algorithm:

View File

@ -23,7 +23,7 @@ primes = set(range(3, NUM_PRIMES, 2))
primes.add(2) primes.add(2)
prime: int prime: int
for prime in range(3, ceil(NUM_PRIMES ** 0.5), 2): for prime in range(3, ceil(NUM_PRIMES**0.5), 2):
if prime not in primes: if prime not in primes:
continue continue
primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime)))

View File

@ -91,7 +91,7 @@ def solution(limit: int = 1000000) -> int:
while num_cuboids <= limit: while num_cuboids <= limit:
max_cuboid_size += 1 max_cuboid_size += 1
for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1): for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1):
if sqrt(sum_shortest_sides ** 2 + max_cuboid_size ** 2).is_integer(): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2).is_integer():
num_cuboids += ( num_cuboids += (
min(max_cuboid_size, sum_shortest_sides // 2) min(max_cuboid_size, sum_shortest_sides // 2)
- max(1, sum_shortest_sides - max_cuboid_size) - max(1, sum_shortest_sides - max_cuboid_size)

View File

@ -12,7 +12,7 @@ How many starting numbers below ten million will arrive at 89?
""" """
DIGITS_SQUARED = [digit ** 2 for digit in range(10)] DIGITS_SQUARED = [digit**2 for digit in range(10)]
def next_number(number: int) -> int: def next_number(number: int) -> int:

View File

@ -34,7 +34,7 @@ def solution(n: int = 10) -> str:
""" """
if not isinstance(n, int) or n < 0: if not isinstance(n, int) or n < 0:
raise ValueError("Invalid input") raise ValueError("Invalid input")
MODULUS = 10 ** n MODULUS = 10**n
NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1 NUMBER = 28433 * (pow(2, 7830457, MODULUS)) + 1
return str(NUMBER % MODULUS) return str(NUMBER % MODULUS)

View File

@ -175,15 +175,15 @@ def question_function(variable: int) -> int:
return ( return (
1 1
- variable - variable
+ variable ** 2 + variable**2
- variable ** 3 - variable**3
+ variable ** 4 + variable**4
- variable ** 5 - variable**5
+ variable ** 6 + variable**6
- variable ** 7 - variable**7
+ variable ** 8 + variable**8
- variable ** 9 - variable**9
+ variable ** 10 + variable**10
) )

View File

@ -35,7 +35,7 @@ def solution() -> int:
Returns the sum of all numbers less than 1e8 that are both palindromic and Returns the sum of all numbers less than 1e8 that are both palindromic and
can be written as the sum of consecutive squares. can be written as the sum of consecutive squares.
""" """
LIMIT = 10 ** 8 LIMIT = 10**8
answer = set() answer = set()
first_square = 1 first_square = 1
sum_squares = 5 sum_squares = 5
@ -45,9 +45,9 @@ def solution() -> int:
if is_palindrome(sum_squares): if is_palindrome(sum_squares):
answer.add(sum_squares) answer.add(sum_squares)
last_square += 1 last_square += 1
sum_squares += last_square ** 2 sum_squares += last_square**2
first_square += 1 first_square += 1
sum_squares = first_square ** 2 + (first_square + 1) ** 2 sum_squares = first_square**2 + (first_square + 1) ** 2
return sum(answer) return sum(answer)

View File

@ -58,15 +58,15 @@ def next_point(
# y^2 + 4x^2 = 100 # y^2 + 4x^2 = 100
# y - b = m * (x - a) # y - b = m * (x - a)
# ==> A x^2 + B x + C = 0 # ==> A x^2 + B x + C = 0
quadratic_term = outgoing_gradient ** 2 + 4 quadratic_term = outgoing_gradient**2 + 4
linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x)
constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100
x_minus = ( x_minus = (
-linear_term - sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term) -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term) ) / (2 * quadratic_term)
x_plus = ( x_plus = (
-linear_term + sqrt(linear_term ** 2 - 4 * quadratic_term * constant_term) -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term)
) / (2 * quadratic_term) ) / (2 * quadratic_term)
# two solutions, one of which is our input point # two solutions, one of which is our input point

View File

@ -1,87 +0,0 @@
"""
Problem 145: https://projecteuler.net/problem=145
Name: How many reversible numbers are there below one-billion?
Some positive integers n have the property that the
sum [ n + reverse(n) ] consists entirely of odd (decimal) digits.
For instance, 36 + 63 = 99 and 409 + 904 = 1313.
We will call such numbers reversible; so 36, 63, 409, and 904 are reversible.
Leading zeroes are not allowed in either n or reverse(n).
There are 120 reversible numbers below one-thousand.
How many reversible numbers are there below one-billion (10^9)?
Solution:
Here a brute force solution is used to find and count the reversible numbers.
"""
from __future__ import annotations
def check_if_odd(sum: int = 36) -> int:
"""
Check if the last digit in the sum is even or odd. If even return 0.
If odd then floor division by 10 is used to remove the last number.
Process continues until sum becomes 0 because no more numbers.
>>> check_if_odd(36)
0
>>> check_if_odd(33)
1
"""
while sum > 0:
if (sum % 10) % 2 == 0:
return 0
sum = sum // 10
return 1
def find_reverse_number(number: int = 36) -> int:
"""
Reverses the given number. Does not work with number that end in zero.
>>> find_reverse_number(36)
63
>>> find_reverse_number(409)
904
"""
reverse = 0
while number > 0:
temp = number % 10
reverse = reverse * 10 + temp
number = number // 10
return reverse
def solution(number: int = 1000000000) -> int:
"""
Loops over the range of numbers.
Checks if they have ending zeros which disqualifies them from being reversible.
If that condition is passed it generates the reversed number.
Then sum up n and reverse(n).
Then check if all the numbers in the sum are odd. If true add to the answer.
>>> solution(1000000000)
608720
>>> solution(1000000)
18720
>>> solution(1000000)
18720
>>> solution(1000)
120
"""
answer = 0
for x in range(1, number):
if x % 10 != 0:
reversed_number = find_reverse_number(x)
sum = x + reversed_number
answer += check_if_odd(sum)
return answer
if __name__ == "__main__":
print(f"{solution() = }")

View File

@ -25,8 +25,8 @@ def solution(limit: int = 1000000) -> int:
answer = 0 answer = 0
for outer_width in range(3, (limit // 4) + 2): for outer_width in range(3, (limit // 4) + 2):
if outer_width ** 2 > limit: if outer_width**2 > limit:
hole_width_lower_bound = max(ceil(sqrt(outer_width ** 2 - limit)), 1) hole_width_lower_bound = max(ceil(sqrt(outer_width**2 - limit)), 1)
else: else:
hole_width_lower_bound = 1 hole_width_lower_bound = 1
if (outer_width - hole_width_lower_bound) % 2: if (outer_width - hole_width_lower_bound) % 2:

View File

@ -61,7 +61,7 @@ def is_sq(number: int) -> bool:
>>> is_sq(1000000) >>> is_sq(1000000)
True True
""" """
sq: int = int(number ** 0.5) sq: int = int(number**0.5)
return number == sq * sq return number == sq * sq

View File

@ -59,7 +59,7 @@ def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int:
# exponentiation # exponentiation
result = base result = base
for i in range(1, height): for i in range(1, height):
result = _modexpt(base, result, 10 ** digits) result = _modexpt(base, result, 10**digits)
return result return result

View File

@ -82,10 +82,10 @@ def get_primes_squared(max_number: int) -> list[int]:
if non_primes[num]: if non_primes[num]:
continue continue
for num_counter in range(num ** 2, max_prime + 1, num): for num_counter in range(num**2, max_prime + 1, num):
non_primes[num_counter] = True non_primes[num_counter] = True
primes.append(num ** 2) primes.append(num**2)
return primes return primes

View File

@ -63,7 +63,7 @@ def solution() -> float:
colin_totals_frequencies[min_colin_total:peter_total] colin_totals_frequencies[min_colin_total:peter_total]
) )
total_games_number = (4 ** 9) * (6 ** 6) total_games_number = (4**9) * (6**6)
peter_win_probability = peter_wins_count / total_games_number peter_win_probability = peter_wins_count / total_games_number
rounded_peter_win_probability = round(peter_win_probability, ndigits=7) rounded_peter_win_probability = round(peter_win_probability, ndigits=7)

View File

@ -81,7 +81,7 @@ def solution(max_proportion: float = 1 / 12345) -> int:
integer = 3 integer = 3
while True: while True:
partition_candidate = (integer ** 2 - 1) / 4 partition_candidate = (integer**2 - 1) / 4
# if candidate is an integer, then there is a partition for k # if candidate is an integer, then there is a partition for k
if partition_candidate == int(partition_candidate): if partition_candidate == int(partition_candidate):
partition_candidate = int(partition_candidate) partition_candidate = int(partition_candidate)

View File

@ -35,7 +35,7 @@ def prime_sieve(n: int) -> list:
is_prime[1] = False is_prime[1] = False
is_prime[2] = True is_prime[2] = True
for i in range(3, int(n ** 0.5 + 1), 2): for i in range(3, int(n**0.5 + 1), 2):
index = i * 2 index = i * 2
while index < n: while index < n:
is_prime[index] = False is_prime[index] = False
@ -69,11 +69,11 @@ def solution(limit: int = 999_966_663_333) -> int:
prime_index = 0 prime_index = 0
last_prime = primes[prime_index] last_prime = primes[prime_index]
while (last_prime ** 2) <= limit: while (last_prime**2) <= limit:
next_prime = primes[prime_index + 1] next_prime = primes[prime_index + 1]
lower_bound = last_prime ** 2 lower_bound = last_prime**2
upper_bound = next_prime ** 2 upper_bound = next_prime**2
# Get numbers divisible by lps(current) # Get numbers divisible by lps(current)
current = lower_bound + last_prime current = lower_bound + last_prime

View File

@ -48,8 +48,8 @@ def solution(exponent: int = 30) -> int:
# To find how many total games were lost for a given exponent x, # To find how many total games were lost for a given exponent x,
# we need to find the Fibonacci number F(x+2). # we need to find the Fibonacci number F(x+2).
fibonacci_index = exponent + 2 fibonacci_index = exponent + 2
phi = (1 + 5 ** 0.5) / 2 phi = (1 + 5**0.5) / 2
fibonacci = (phi ** fibonacci_index - (phi - 1) ** fibonacci_index) / 5 ** 0.5 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5
return int(fibonacci) return int(fibonacci)

View File

@ -14,7 +14,7 @@ Find a(10^15)
ks = [k for k in range(2, 20 + 1)] ks = [k for k in range(2, 20 + 1)]
base = [10 ** k for k in range(ks[-1] + 1)] base = [10**k for k in range(ks[-1] + 1)]
memo: dict[int, dict[int, list[list[int]]]] = {} memo: dict[int, dict[int, list[list[int]]]] = {}
@ -168,7 +168,7 @@ def add(digits, k, addend):
digits.append(digit) digits.append(digit)
def solution(n: int = 10 ** 15) -> int: def solution(n: int = 10**15) -> int:
""" """
returns n-th term of sequence returns n-th term of sequence
@ -193,7 +193,7 @@ def solution(n: int = 10 ** 15) -> int:
a_n = 0 a_n = 0
for j in range(len(digits)): for j in range(len(digits)):
a_n += digits[j] * 10 ** j a_n += digits[j] * 10**j
return a_n return a_n

View File

@ -39,7 +39,7 @@ def dj_oracle(case: str, num_qubits: int) -> q.QuantumCircuit:
if case == "balanced": if case == "balanced":
# First generate a random number that tells us which CNOTs to # First generate a random number that tells us which CNOTs to
# wrap in X-gates: # wrap in X-gates:
b = np.random.randint(1, 2 ** num_qubits) b = np.random.randint(1, 2**num_qubits)
# Next, format 'b' as a binary string of length 'n', padded with zeros: # Next, format 'b' as a binary string of length 'n', padded with zeros:
b_str = format(b, f"0{num_qubits}b") b_str = format(b, f"0{num_qubits}b")
# Next, we place the first X-gates. Each digit in our binary string # Next, we place the first X-gates. Each digit in our binary string

View File

@ -166,7 +166,7 @@ if __name__ == "__main__":
doctest.testmod() doctest.testmod()
def test_f1(x, y): def test_f1(x, y):
return (x ** 2) + (y ** 2) return (x**2) + (y**2)
# starting the problem with initial coordinates (3, 4) # starting the problem with initial coordinates (3, 4)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
@ -187,7 +187,7 @@ if __name__ == "__main__":
) )
def test_f2(x, y): def test_f2(x, y):
return (3 * x ** 2) - (6 * y) return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = hill_climbing(prob, find_max=True) local_min = hill_climbing(prob, find_max=True)

View File

@ -97,7 +97,7 @@ def simulated_annealing(
if __name__ == "__main__": if __name__ == "__main__":
def test_f1(x, y): def test_f1(x, y):
return (x ** 2) + (y ** 2) return (x**2) + (y**2)
# starting the problem with initial coordinates (12, 47) # starting the problem with initial coordinates (12, 47)
prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1)
@ -120,7 +120,7 @@ if __name__ == "__main__":
) )
def test_f2(x, y): def test_f2(x, y):
return (3 * x ** 2) - (6 * y) return (3 * x**2) - (6 * y)
prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1)
local_min = simulated_annealing(prob, find_max=False, visualization=True) local_min = simulated_annealing(prob, find_max=False, visualization=True)