mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-27 15:01:08 +00:00
MAINT: Updated f-string method (#6230)
* MAINT: Used f-string method Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * Updated files with f-string method * Update rsa_key_generator.py * Update rsa_key_generator.py * Update elgamal_key_generator.py * Update lru_cache.py I don't think this change is efficient but it might tackle the error as the error was due to using long character lines. * Update lru_cache.py * Update lru_cache.py Co-authored-by: cyai <seriesscar@gmail.com> Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
parent
0a0f4986e4
commit
2d5dd6f132
|
@ -38,9 +38,7 @@ def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, i
|
||||||
|
|
||||||
|
|
||||||
def make_key_files(name: str, keySize: int) -> None:
|
def make_key_files(name: str, keySize: int) -> None:
|
||||||
if os.path.exists("%s_pubkey.txt" % name) or os.path.exists(
|
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
|
||||||
"%s_privkey.txt" % name
|
|
||||||
):
|
|
||||||
print("\nWARNING:")
|
print("\nWARNING:")
|
||||||
print(
|
print(
|
||||||
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
|
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
|
||||||
|
@ -50,14 +48,14 @@ def make_key_files(name: str, keySize: int) -> None:
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
publicKey, privateKey = generate_key(keySize)
|
publicKey, privateKey = generate_key(keySize)
|
||||||
print("\nWriting public key to file %s_pubkey.txt..." % name)
|
print(f"\nWriting public key to file {name}_pubkey.txt...")
|
||||||
with open("%s_pubkey.txt" % name, "w") as fo:
|
with open(f"{name}_pubkey.txt", "w") as fo:
|
||||||
fo.write(
|
fo.write(
|
||||||
"%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3])
|
"%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3])
|
||||||
)
|
)
|
||||||
|
|
||||||
print("Writing private key to file %s_privkey.txt..." % name)
|
print(f"Writing private key to file {name}_privkey.txt...")
|
||||||
with open("%s_privkey.txt" % name, "w") as fo:
|
with open(f"{name}_privkey.txt", "w") as fo:
|
||||||
fo.write("%d,%d" % (privateKey[0], privateKey[1]))
|
fo.write("%d,%d" % (privateKey[0], privateKey[1]))
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -129,7 +129,7 @@ def main() -> None:
|
||||||
|
|
||||||
message = input("\nEnter message: ")
|
message = input("\nEnter message: ")
|
||||||
pubkey_filename = "rsa_pubkey.txt"
|
pubkey_filename = "rsa_pubkey.txt"
|
||||||
print("Encrypting and writing to %s..." % (filename))
|
print(f"Encrypting and writing to {filename}...")
|
||||||
encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message)
|
encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message)
|
||||||
|
|
||||||
print("\nEncrypted text:")
|
print("\nEncrypted text:")
|
||||||
|
@ -137,7 +137,7 @@ def main() -> None:
|
||||||
|
|
||||||
elif mode == "decrypt":
|
elif mode == "decrypt":
|
||||||
privkey_filename = "rsa_privkey.txt"
|
privkey_filename = "rsa_privkey.txt"
|
||||||
print("Reading from %s and decrypting..." % (filename))
|
print(f"Reading from {filename} and decrypting...")
|
||||||
decrypted_text = read_from_file_and_decrypt(filename, privkey_filename)
|
decrypted_text = read_from_file_and_decrypt(filename, privkey_filename)
|
||||||
print("writing decryption to rsa_decryption.txt...")
|
print("writing decryption to rsa_decryption.txt...")
|
||||||
with open("rsa_decryption.txt", "w") as dec:
|
with open("rsa_decryption.txt", "w") as dec:
|
||||||
|
|
|
@ -34,9 +34,7 @@ def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]:
|
||||||
|
|
||||||
|
|
||||||
def makeKeyFiles(name: str, keySize: int) -> None:
|
def makeKeyFiles(name: str, keySize: int) -> None:
|
||||||
if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists(
|
if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"):
|
||||||
"%s_privkey.txt" % (name)
|
|
||||||
):
|
|
||||||
print("\nWARNING:")
|
print("\nWARNING:")
|
||||||
print(
|
print(
|
||||||
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
|
'"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n'
|
||||||
|
@ -46,12 +44,12 @@ def makeKeyFiles(name: str, keySize: int) -> None:
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
||||||
publicKey, privateKey = generateKey(keySize)
|
publicKey, privateKey = generateKey(keySize)
|
||||||
print("\nWriting public key to file %s_pubkey.txt..." % name)
|
print(f"\nWriting public key to file {name}_pubkey.txt...")
|
||||||
with open("%s_pubkey.txt" % name, "w") as out_file:
|
with open(f"{name}_pubkey.txt", "w") as out_file:
|
||||||
out_file.write(f"{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(f"Writing private key to file {name}_privkey.txt...")
|
||||||
with open("%s_privkey.txt" % name, "w") as out_file:
|
with open(f"{name}_privkey.txt", "w") as out_file:
|
||||||
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")
|
out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -10,7 +10,7 @@ text. The type of transposition cipher demonstrated under is the ROUTE cipher.
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
message = input("Enter message: ")
|
message = input("Enter message: ")
|
||||||
key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
|
key = int(input(f"Enter key [2-{len(message) - 1}]: "))
|
||||||
mode = input("Encryption/Decryption [e/d]: ")
|
mode = input("Encryption/Decryption [e/d]: ")
|
||||||
|
|
||||||
if mode.lower().startswith("e"):
|
if mode.lower().startswith("e"):
|
||||||
|
@ -19,7 +19,7 @@ def main() -> None:
|
||||||
text = decryptMessage(key, message)
|
text = decryptMessage(key, message)
|
||||||
|
|
||||||
# Append pipe symbol (vertical bar) to identify spaces at the end.
|
# Append pipe symbol (vertical bar) to identify spaces at the end.
|
||||||
print("Output:\n%s" % (text + "|"))
|
print(f"Output:\n{text + '|'}")
|
||||||
|
|
||||||
|
|
||||||
def encryptMessage(key: int, message: str) -> str:
|
def encryptMessage(key: int, message: str) -> str:
|
||||||
|
|
|
@ -12,10 +12,10 @@ def main() -> None:
|
||||||
mode = input("Encrypt/Decrypt [e/d]: ")
|
mode = input("Encrypt/Decrypt [e/d]: ")
|
||||||
|
|
||||||
if not os.path.exists(inputFile):
|
if not os.path.exists(inputFile):
|
||||||
print("File %s does not exist. Quitting..." % inputFile)
|
print(f"File {inputFile} does not exist. Quitting...")
|
||||||
sys.exit()
|
sys.exit()
|
||||||
if os.path.exists(outputFile):
|
if os.path.exists(outputFile):
|
||||||
print("Overwrite %s? [y/n]" % outputFile)
|
print(f"Overwrite {outputFile}? [y/n]")
|
||||||
response = input("> ")
|
response = input("> ")
|
||||||
if not response.lower().startswith("y"):
|
if not response.lower().startswith("y"):
|
||||||
sys.exit()
|
sys.exit()
|
||||||
|
|
|
@ -13,7 +13,7 @@ def main() -> None:
|
||||||
mode = "decrypt"
|
mode = "decrypt"
|
||||||
translated = decryptMessage(key, message)
|
translated = decryptMessage(key, message)
|
||||||
|
|
||||||
print("\n%sed message:" % mode.title())
|
print(f"\n{mode.title()}ed message:")
|
||||||
print(translated)
|
print(translated)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -15,7 +15,7 @@ class Node:
|
||||||
|
|
||||||
if self.left is None and self.right is None:
|
if self.left is None and self.right is None:
|
||||||
return str(self.value)
|
return str(self.value)
|
||||||
return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1)
|
return pformat({f"{self.value}": (self.left, self.right)}, indent=1)
|
||||||
|
|
||||||
|
|
||||||
class BinarySearchTree:
|
class BinarySearchTree:
|
||||||
|
|
|
@ -96,7 +96,7 @@ if __name__ == "__main__":
|
||||||
|
|
||||||
# Pulling Data (Output)
|
# Pulling Data (Output)
|
||||||
while inp in ("e", "E"):
|
while inp in ("e", "E"):
|
||||||
print("%s" % format(pull(), "#04x"))
|
print(f"{format(pull(), '#04x')}")
|
||||||
print(buffer_space)
|
print(buffer_space)
|
||||||
print(params_space)
|
print(params_space)
|
||||||
inp = input("(e)exit? ").strip()
|
inp = input("(e)exit? ").strip()
|
||||||
|
|
|
@ -47,9 +47,9 @@ def main():
|
||||||
y_pred = model.predict(X_test)
|
y_pred = model.predict(X_test)
|
||||||
|
|
||||||
# The mean squared error
|
# The mean squared error
|
||||||
print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred))
|
print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}")
|
||||||
# Explained variance score: 1 is perfect prediction
|
# Explained variance score: 1 is perfect prediction
|
||||||
print("Test Variance score: %.2f" % r2_score(y_test, y_pred))
|
print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}")
|
||||||
|
|
||||||
# So let's run the model against the test data
|
# So let's run the model against the test data
|
||||||
fig, ax = plt.subplots()
|
fig, ax = plt.subplots()
|
||||||
|
|
|
@ -164,9 +164,7 @@ def kmeans(
|
||||||
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
|
num_changed = np.sum(prev_cluster_assignment != cluster_assignment)
|
||||||
if verbose:
|
if verbose:
|
||||||
print(
|
print(
|
||||||
" {:5d} elements changed their cluster assignment.".format(
|
f" {num_changed:5d} elements changed their cluster assignment."
|
||||||
num_changed
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Record heterogeneity convergence metric
|
# Record heterogeneity convergence metric
|
||||||
|
|
|
@ -99,7 +99,7 @@ def main():
|
||||||
len_result = theta.shape[1]
|
len_result = theta.shape[1]
|
||||||
print("Resultant Feature vector : ")
|
print("Resultant Feature vector : ")
|
||||||
for i in range(0, len_result):
|
for i in range(0, len_result):
|
||||||
print("%.5f" % (theta[0, i]))
|
print(f"{theta[0, i]:.5f}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|
|
@ -256,7 +256,7 @@ if __name__ == "__main__":
|
||||||
v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
|
v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5
|
||||||
print(f"u is {u}")
|
print(f"u is {u}")
|
||||||
print(f"v is {v}")
|
print(f"v is {v}")
|
||||||
print("uv^T is %s" % (u * v.transpose()))
|
print(f"uv^T is {u * v.transpose()}")
|
||||||
# Sherman Morrison
|
# Sherman Morrison
|
||||||
print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}")
|
print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}")
|
||||||
|
|
||||||
|
|
|
@ -71,7 +71,7 @@ class CNN:
|
||||||
with open(save_path, "wb") as f:
|
with open(save_path, "wb") as f:
|
||||||
pickle.dump(model_dic, f)
|
pickle.dump(model_dic, f)
|
||||||
|
|
||||||
print("Model saved: %s" % save_path)
|
print(f"Model saved: {save_path}")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def ReadModel(cls, model_path):
|
def ReadModel(cls, model_path):
|
||||||
|
@ -303,7 +303,7 @@ class CNN:
|
||||||
plt.show()
|
plt.show()
|
||||||
|
|
||||||
print("------------------Training Complished---------------------")
|
print("------------------Training Complished---------------------")
|
||||||
print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse))
|
print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}"))
|
||||||
if draw_e:
|
if draw_e:
|
||||||
draw_error()
|
draw_error()
|
||||||
return mse
|
return mse
|
||||||
|
|
|
@ -21,8 +21,9 @@ class DoubleLinkedListNode(Generic[T, U]):
|
||||||
self.prev: DoubleLinkedListNode[T, U] | None = None
|
self.prev: DoubleLinkedListNode[T, U] | None = None
|
||||||
|
|
||||||
def __repr__(self) -> str:
|
def __repr__(self) -> str:
|
||||||
return "Node: key: {}, val: {}, has next: {}, has prev: {}".format(
|
return (
|
||||||
self.key, self.val, self.next is not None, self.prev is not None
|
f"Node: key: {self.key}, val: {self.val}, "
|
||||||
|
f"has next: {bool(self.next)}, has prev: {bool(self.prev)}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -69,7 +69,7 @@ def procentual_proximity(
|
||||||
|
|
||||||
# weight not 0 or 1
|
# weight not 0 or 1
|
||||||
else:
|
else:
|
||||||
raise ValueError("Invalid weight of %f provided" % (weight))
|
raise ValueError(f"Invalid weight of {weight:f} provided")
|
||||||
|
|
||||||
score_lists.append(score)
|
score_lists.append(score)
|
||||||
|
|
||||||
|
|
|
@ -111,7 +111,7 @@ def calculate_average_times(
|
||||||
for i in range(no_of_processes):
|
for i in range(no_of_processes):
|
||||||
total_waiting_time = total_waiting_time + waiting_time[i]
|
total_waiting_time = total_waiting_time + waiting_time[i]
|
||||||
total_turn_around_time = total_turn_around_time + turn_around_time[i]
|
total_turn_around_time = total_turn_around_time + turn_around_time[i]
|
||||||
print("Average waiting time = %.5f" % (total_waiting_time / no_of_processes))
|
print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}")
|
||||||
print("Average turn around time =", total_turn_around_time / no_of_processes)
|
print("Average turn around time =", total_turn_around_time / no_of_processes)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -25,14 +25,14 @@ def build_tree():
|
||||||
q.put(tree_node)
|
q.put(tree_node)
|
||||||
while not q.empty():
|
while not q.empty():
|
||||||
node_found = q.get()
|
node_found = q.get()
|
||||||
msg = "Enter the left node of %s: " % node_found.data
|
msg = f"Enter the left node of {node_found.data}: "
|
||||||
check = input(msg).strip().lower() or "n"
|
check = input(msg).strip().lower() or "n"
|
||||||
if check == "n":
|
if check == "n":
|
||||||
return tree_node
|
return tree_node
|
||||||
left_node = TreeNode(int(check))
|
left_node = TreeNode(int(check))
|
||||||
node_found.left = left_node
|
node_found.left = left_node
|
||||||
q.put(left_node)
|
q.put(left_node)
|
||||||
msg = "Enter the right node of %s: " % node_found.data
|
msg = f"Enter the right node of {node_found.data}: "
|
||||||
check = input(msg).strip().lower() or "n"
|
check = input(msg).strip().lower() or "n"
|
||||||
if check == "n":
|
if check == "n":
|
||||||
return tree_node
|
return tree_node
|
||||||
|
|
|
@ -31,28 +31,28 @@ def compute_transform_tables(
|
||||||
|
|
||||||
for i in range(1, len_source_seq + 1):
|
for i in range(1, len_source_seq + 1):
|
||||||
costs[i][0] = i * delete_cost
|
costs[i][0] = i * delete_cost
|
||||||
ops[i][0] = "D%c" % source_seq[i - 1]
|
ops[i][0] = f"D{source_seq[i - 1]:c}"
|
||||||
|
|
||||||
for i in range(1, len_destination_seq + 1):
|
for i in range(1, len_destination_seq + 1):
|
||||||
costs[0][i] = i * insert_cost
|
costs[0][i] = i * insert_cost
|
||||||
ops[0][i] = "I%c" % destination_seq[i - 1]
|
ops[0][i] = f"I{destination_seq[i - 1]:c}"
|
||||||
|
|
||||||
for i in range(1, len_source_seq + 1):
|
for i in range(1, len_source_seq + 1):
|
||||||
for j in range(1, len_destination_seq + 1):
|
for j in range(1, len_destination_seq + 1):
|
||||||
if source_seq[i - 1] == destination_seq[j - 1]:
|
if source_seq[i - 1] == destination_seq[j - 1]:
|
||||||
costs[i][j] = costs[i - 1][j - 1] + copy_cost
|
costs[i][j] = costs[i - 1][j - 1] + copy_cost
|
||||||
ops[i][j] = "C%c" % source_seq[i - 1]
|
ops[i][j] = f"C{source_seq[i - 1]:c}"
|
||||||
else:
|
else:
|
||||||
costs[i][j] = costs[i - 1][j - 1] + replace_cost
|
costs[i][j] = costs[i - 1][j - 1] + replace_cost
|
||||||
ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1])
|
ops[i][j] = f"R{source_seq[i - 1]:c}" + str(destination_seq[j - 1])
|
||||||
|
|
||||||
if costs[i - 1][j] + delete_cost < costs[i][j]:
|
if costs[i - 1][j] + delete_cost < costs[i][j]:
|
||||||
costs[i][j] = costs[i - 1][j] + delete_cost
|
costs[i][j] = costs[i - 1][j] + delete_cost
|
||||||
ops[i][j] = "D%c" % source_seq[i - 1]
|
ops[i][j] = f"D{source_seq[i - 1]:c}"
|
||||||
|
|
||||||
if costs[i][j - 1] + insert_cost < costs[i][j]:
|
if costs[i][j - 1] + insert_cost < costs[i][j]:
|
||||||
costs[i][j] = costs[i][j - 1] + insert_cost
|
costs[i][j] = costs[i][j - 1] + insert_cost
|
||||||
ops[i][j] = "I%c" % destination_seq[j - 1]
|
ops[i][j] = f"I{destination_seq[j - 1]:c}"
|
||||||
|
|
||||||
return costs, ops
|
return costs, ops
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user