mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Change occurrences of str.format to f-strings (#4118)
* f-string update rsa_cipher.py * f-string update rsa_key_generator.py * f-string update burrows_wheeler.py * f-string update non_recursive_segment_tree.py * f-string update red_black_tree.py * f-string update deque_doubly.py * f-string update climbing_stairs.py * f-string update iterating_through_submasks.py * f-string update knn_sklearn.py * f-string update 3n_plus_1.py * f-string update quadratic_equations_complex_numbers.py * f-string update nth_fibonacci_using_matrix_exponentiation.py * f-string update sherman_morrison.py * f-string update levenshtein_distance.py * fix lines that were too long
This commit is contained in:
parent
f680806894
commit
61f3119467
|
@ -118,7 +118,7 @@ def encryptAndWriteToFile(
|
||||||
for i in range(len(encryptedBlocks)):
|
for i in range(len(encryptedBlocks)):
|
||||||
encryptedBlocks[i] = str(encryptedBlocks[i])
|
encryptedBlocks[i] = str(encryptedBlocks[i])
|
||||||
encryptedContent = ",".join(encryptedBlocks)
|
encryptedContent = ",".join(encryptedBlocks)
|
||||||
encryptedContent = "{}_{}_{}".format(len(message), blockSize, encryptedContent)
|
encryptedContent = f"{len(message)}_{blockSize}_{encryptedContent}"
|
||||||
with open(messageFilename, "w") as fo:
|
with open(messageFilename, "w") as fo:
|
||||||
fo.write(encryptedContent)
|
fo.write(encryptedContent)
|
||||||
return encryptedContent
|
return encryptedContent
|
||||||
|
|
|
@ -49,11 +49,11 @@ def makeKeyFiles(name: int, keySize: int) -> None:
|
||||||
publicKey, privateKey = generateKey(keySize)
|
publicKey, privateKey = generateKey(keySize)
|
||||||
print("\nWriting public key to file %s_pubkey.txt..." % name)
|
print("\nWriting public key to file %s_pubkey.txt..." % name)
|
||||||
with open("%s_pubkey.txt" % name, "w") as out_file:
|
with open("%s_pubkey.txt" % name, "w") as out_file:
|
||||||
out_file.write("{},{},{}".format(keySize, publicKey[0], publicKey[1]))
|
out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}")
|
||||||
|
|
||||||
print("Writing private key to file %s_privkey.txt..." % name)
|
print("Writing private key to file %s_privkey.txt..." % name)
|
||||||
with open("%s_privkey.txt" % name, "w") as out_file:
|
with open("%s_privkey.txt" % name, "w") as out_file:
|
||||||
out_file.write("{},{},{}".format(keySize, privateKey[0], privateKey[1]))
|
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -157,11 +157,12 @@ if __name__ == "__main__":
|
||||||
entry_msg = "Provide a string that I will generate its BWT transform: "
|
entry_msg = "Provide a string that I will generate its BWT transform: "
|
||||||
s = input(entry_msg).strip()
|
s = input(entry_msg).strip()
|
||||||
result = bwt_transform(s)
|
result = bwt_transform(s)
|
||||||
bwt_output_msg = "Burrows Wheeler transform for string '{}' results in '{}'"
|
print(
|
||||||
print(bwt_output_msg.format(s, result["bwt_string"]))
|
f"Burrows Wheeler transform for string '{s}' results "
|
||||||
original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"])
|
f"in '{result['bwt_string']}'"
|
||||||
fmt = (
|
)
|
||||||
"Reversing Burrows Wheeler transform for entry '{}' we get original"
|
original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"])
|
||||||
" string '{}'"
|
print(
|
||||||
|
f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' "
|
||||||
|
f"we get original string '{original_string}'"
|
||||||
)
|
)
|
||||||
print(fmt.format(result["bwt_string"], original_string))
|
|
||||||
|
|
|
@ -49,7 +49,7 @@ class SegmentTree:
|
||||||
:param arr: list of elements for the segment tree
|
:param arr: list of elements for the segment tree
|
||||||
:param fnc: commutative function for combine two elements
|
:param fnc: commutative function for combine two elements
|
||||||
|
|
||||||
>>> SegmentTree(['a', 'b', 'c'], lambda a, b: '{}{}'.format(a, b)).query(0, 2)
|
>>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2)
|
||||||
'abc'
|
'abc'
|
||||||
>>> SegmentTree([(1, 2), (2, 3), (3, 4)],
|
>>> SegmentTree([(1, 2), (2, 3), (3, 4)],
|
||||||
... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2)
|
... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2)
|
||||||
|
|
|
@ -475,11 +475,13 @@ class RedBlackTree:
|
||||||
from pprint import pformat
|
from pprint import pformat
|
||||||
|
|
||||||
if self.left is None and self.right is None:
|
if self.left is None and self.right is None:
|
||||||
return "'{} {}'".format(self.label, (self.color and "red") or "blk")
|
return f"'{self.label} {(self.color and 'red') or 'blk'}'"
|
||||||
return pformat(
|
return pformat(
|
||||||
{
|
{
|
||||||
"%s %s"
|
f"{self.label} {(self.color and 'red') or 'blk'}": (
|
||||||
% (self.label, (self.color and "red") or "blk"): (self.left, self.right)
|
self.left,
|
||||||
|
self.right,
|
||||||
|
)
|
||||||
},
|
},
|
||||||
indent=1,
|
indent=1,
|
||||||
)
|
)
|
||||||
|
|
|
@ -20,8 +20,8 @@ class _DoublyLinkedBase:
|
||||||
self._next = link_n
|
self._next = link_n
|
||||||
|
|
||||||
def has_next_and_prev(self):
|
def has_next_and_prev(self):
|
||||||
return " Prev -> {}, Next -> {}".format(
|
return (
|
||||||
self._prev is not None, self._next is not None
|
f" Prev -> {self._prev is not None}, Next -> {self._next is not None}"
|
||||||
)
|
)
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
|
|
@ -25,8 +25,9 @@ def climb_stairs(n: int) -> int:
|
||||||
...
|
...
|
||||||
AssertionError: n needs to be positive integer, your input -7
|
AssertionError: n needs to be positive integer, your input -7
|
||||||
"""
|
"""
|
||||||
fmt = "n needs to be positive integer, your input {}"
|
assert (
|
||||||
assert isinstance(n, int) and n > 0, fmt.format(n)
|
isinstance(n, int) and n > 0
|
||||||
|
), f"n needs to be positive integer, your input {n}"
|
||||||
if n == 1:
|
if n == 1:
|
||||||
return 1
|
return 1
|
||||||
dp = [0] * (n + 1)
|
dp = [0] * (n + 1)
|
||||||
|
|
|
@ -37,8 +37,9 @@ def list_of_submasks(mask: int) -> list[int]:
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
fmt = "mask needs to be positive integer, your input {}"
|
assert (
|
||||||
assert isinstance(mask, int) and mask > 0, fmt.format(mask)
|
isinstance(mask, int) and mask > 0
|
||||||
|
), f"mask needs to be positive integer, your input {mask}"
|
||||||
|
|
||||||
"""
|
"""
|
||||||
first submask iterated will be mask itself then operation will be performed
|
first submask iterated will be mask itself then operation will be performed
|
||||||
|
|
|
@ -26,6 +26,6 @@ X_new = [[1, 2, 1, 4], [2, 3, 4, 5]]
|
||||||
prediction = knn.predict(X_new)
|
prediction = knn.predict(X_new)
|
||||||
|
|
||||||
print(
|
print(
|
||||||
"\nNew array: \n {}"
|
f"\nNew array: \n {X_new}\n\nTarget Names Prediction: \n"
|
||||||
"\n\nTarget Names Prediction: \n {}".format(X_new, iris["target_names"][prediction])
|
f" {iris['target_names'][prediction]}"
|
||||||
)
|
)
|
||||||
|
|
|
@ -9,7 +9,7 @@ def n31(a: int) -> tuple[list[int], int]:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not isinstance(a, int):
|
if not isinstance(a, int):
|
||||||
raise TypeError("Must be int, not {}".format(type(a).__name__))
|
raise TypeError(f"Must be int, not {type(a).__name__}")
|
||||||
if a < 1:
|
if a < 1:
|
||||||
raise ValueError(f"Given integer must be greater than 1, not {a}")
|
raise ValueError(f"Given integer must be greater than 1, not {a}")
|
||||||
|
|
||||||
|
|
|
@ -30,8 +30,8 @@ def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]:
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
solutions = quadratic_roots(a=5, b=6, c=1)
|
solution1, solution2 = quadratic_roots(a=5, b=6, c=1)
|
||||||
print("The solutions are: {} and {}".format(*solutions))
|
print(f"The solutions are: {solution1} and {solution2}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -71,13 +71,13 @@ def nth_fibonacci_bruteforce(n):
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
fmt = (
|
|
||||||
"{} fibonacci number using matrix exponentiation is {} and using bruteforce "
|
|
||||||
"is {}\n"
|
|
||||||
)
|
|
||||||
for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
|
for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split():
|
||||||
n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000
|
n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000
|
||||||
print(fmt.format(ordinal, nth_fibonacci_matrix(n), nth_fibonacci_bruteforce(n)))
|
print(
|
||||||
|
f"{ordinal} fibonacci number using matrix exponentiation is "
|
||||||
|
f"{nth_fibonacci_matrix(n)} and using bruteforce is "
|
||||||
|
f"{nth_fibonacci_bruteforce(n)}\n"
|
||||||
|
)
|
||||||
# from timeit import timeit
|
# from timeit import timeit
|
||||||
# print(timeit("nth_fibonacci_matrix(1000000)",
|
# print(timeit("nth_fibonacci_matrix(1000000)",
|
||||||
# "from main import nth_fibonacci_matrix", number=5))
|
# "from main import nth_fibonacci_matrix", number=5))
|
||||||
|
|
|
@ -175,9 +175,7 @@ class Matrix:
|
||||||
result[r, c] += self[r, i] * another[i, c]
|
result[r, c] += self[r, i] * another[i, c]
|
||||||
return result
|
return result
|
||||||
else:
|
else:
|
||||||
raise TypeError(
|
raise TypeError(f"Unsupported type given for another ({type(another)})")
|
||||||
"Unsupported type given for another ({})".format(type(another))
|
|
||||||
)
|
|
||||||
|
|
||||||
def transpose(self):
|
def transpose(self):
|
||||||
"""
|
"""
|
||||||
|
@ -260,7 +258,7 @@ if __name__ == "__main__":
|
||||||
print(f"v is {v}")
|
print(f"v is {v}")
|
||||||
print("uv^T is %s" % (u * v.transpose()))
|
print("uv^T is %s" % (u * v.transpose()))
|
||||||
# Sherman Morrison
|
# Sherman Morrison
|
||||||
print("(a + uv^T)^(-1) is {}".format(ainv.ShermanMorrison(u, v)))
|
print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}")
|
||||||
|
|
||||||
def test2():
|
def test2():
|
||||||
import doctest
|
import doctest
|
||||||
|
|
|
@ -69,8 +69,4 @@ if __name__ == "__main__":
|
||||||
second_word = input("Enter the second word:\n").strip()
|
second_word = input("Enter the second word:\n").strip()
|
||||||
|
|
||||||
result = levenshtein_distance(first_word, second_word)
|
result = levenshtein_distance(first_word, second_word)
|
||||||
print(
|
print(f"Levenshtein distance between {first_word} and {second_word} is {result}")
|
||||||
"Levenshtein distance between {} and {} is {}".format(
|
|
||||||
first_word, second_word, result
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user