From 13ceb2b56271be287cdc45251ca7cf590e53b980 Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Tue, 5 Jul 2022 22:31:07 +0530 Subject: [PATCH 1/8] MAINT: Used f-string method Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. --- other/lru_cache.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/other/lru_cache.py b/other/lru_cache.py index 98051f89db4f..2c25a0855632 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -21,9 +21,7 @@ def __init__(self, key: T | None, val: U | None): self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: - return "Node: key: {}, val: {}, has next: {}, has prev: {}".format( - self.key, self.val, self.next is not None, self.prev is not None - ) + return f"Node: key: {self.key}, val: {self.val}, has next: {self.next is not None}, has prev: {self.prev is not None}" class DoubleLinkedList(Generic[T, U]): From 3e555c1199795752dc4868e97bbc3bdab4dcdf07 Mon Sep 17 00:00:00 2001 From: cyai Date: Wed, 6 Jul 2022 22:44:01 +0530 Subject: [PATCH 2/8] Updated files with f-string method --- ciphers/elgamal_key_generator.py | 12 ++++++------ ciphers/rsa_cipher.py | 4 ++-- ciphers/rsa_key_generator.py | 12 ++++++------ ciphers/transposition_cipher.py | 4 ++-- ciphers/transposition_cipher_encrypt_decrypt_file.py | 4 ++-- ciphers/vigenere_cipher.py | 2 +- data_structures/binary_tree/binary_search_tree.py | 2 +- hashes/chaos_machine.py | 2 +- machine_learning/gradient_boosting_regressor.py | 4 ++-- machine_learning/k_means_clust.py | 4 +--- machine_learning/linear_regression.py | 2 +- matrix/sherman_morrison.py | 2 +- neural_network/convolution_neural_network.py | 4 ++-- other/scoring_algorithm.py | 2 +- scheduling/shortest_job_first.py | 2 +- searches/binary_tree_traversal.py | 4 ++-- strings/min_cost_string_conversion.py | 12 ++++++------ 17 files changed, 38 insertions(+), 40 deletions(-) diff --git a/ciphers/elgamal_key_generator.py b/ciphers/elgamal_key_generator.py index f557b0e0dc91..93aabac3b56c 100644 --- a/ciphers/elgamal_key_generator.py +++ b/ciphers/elgamal_key_generator.py @@ -38,8 +38,8 @@ def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, i def make_key_files(name: str, keySize: int) -> None: - if os.path.exists("%s_pubkey.txt" % name) or os.path.exists( - "%s_privkey.txt" % name + if os.path.exists(f"{name}_pubkey.txt") or os.path.exists( + f"{name}_privkey.txt" ): print("\nWARNING:") print( @@ -50,14 +50,14 @@ def make_key_files(name: str, keySize: int) -> None: sys.exit() publicKey, privateKey = generate_key(keySize) - print("\nWriting public key to file %s_pubkey.txt..." % name) - with open("%s_pubkey.txt" % name, "w") as fo: + print(f"\nWriting public key to file {name}_pubkey.txt...") + with open(f"{name}_pubkey.txt", "w") as fo: fo.write( "%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]) ) - print("Writing private key to file %s_privkey.txt..." % name) - with open("%s_privkey.txt" % name, "w") as fo: + print(f"Writing private key to file {name}_privkey.txt...") + with open(f"{name}_privkey.txt", "w") as fo: fo.write("%d,%d" % (privateKey[0], privateKey[1])) diff --git a/ciphers/rsa_cipher.py b/ciphers/rsa_cipher.py index 5bb9f9916de5..c6bfaa0fb00c 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -129,7 +129,7 @@ def main() -> None: message = input("\nEnter message: ") 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) print("\nEncrypted text:") @@ -137,7 +137,7 @@ def main() -> None: elif mode == "decrypt": 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) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index 584066d8970f..2e56b1614781 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -34,8 +34,8 @@ def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]: def makeKeyFiles(name: str, keySize: int) -> None: - if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( - "%s_privkey.txt" % (name) + if os.path.exists(f"{name}_pubkey.txt") or os.path.exists( + f"{name}_privkey.txt" ): print("\nWARNING:") print( @@ -46,12 +46,12 @@ def makeKeyFiles(name: str, keySize: int) -> None: sys.exit() publicKey, privateKey = generateKey(keySize) - print("\nWriting public key to file %s_pubkey.txt..." % name) - with open("%s_pubkey.txt" % name, "w") as out_file: + print(f"\nWriting public key to file {name}_pubkey.txt...") + with open(f"{name}_pubkey.txt", "w") as out_file: out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}") - print("Writing private key to file %s_privkey.txt..." % name) - with open("%s_privkey.txt" % name, "w") as out_file: + print(f"Writing private key to file {name}_privkey.txt...") + with open(f"{name}_privkey.txt", "w") as out_file: out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}") diff --git a/ciphers/transposition_cipher.py b/ciphers/transposition_cipher.py index 589bb8cb5cd5..ed9923a6ba46 100644 --- a/ciphers/transposition_cipher.py +++ b/ciphers/transposition_cipher.py @@ -10,7 +10,7 @@ def main() -> None: 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]: ") if mode.lower().startswith("e"): @@ -19,7 +19,7 @@ def main() -> None: text = decryptMessage(key, message) # 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: diff --git a/ciphers/transposition_cipher_encrypt_decrypt_file.py b/ciphers/transposition_cipher_encrypt_decrypt_file.py index b91c73c9f2ad..926a1b36ac44 100644 --- a/ciphers/transposition_cipher_encrypt_decrypt_file.py +++ b/ciphers/transposition_cipher_encrypt_decrypt_file.py @@ -12,10 +12,10 @@ def main() -> None: mode = input("Encrypt/Decrypt [e/d]: ") if not os.path.exists(inputFile): - print("File %s does not exist. Quitting..." % inputFile) + print(f"File {inputFile} does not exist. Quitting...") sys.exit() if os.path.exists(outputFile): - print("Overwrite %s? [y/n]" % outputFile) + print(f"Overwrite {outputFile}? [y/n]") response = input("> ") if not response.lower().startswith("y"): sys.exit() diff --git a/ciphers/vigenere_cipher.py b/ciphers/vigenere_cipher.py index d97a96949fb8..2e3987708d01 100644 --- a/ciphers/vigenere_cipher.py +++ b/ciphers/vigenere_cipher.py @@ -13,7 +13,7 @@ def main() -> None: mode = "decrypt" translated = decryptMessage(key, message) - print("\n%sed message:" % mode.title()) + print(f"\n{mode.title()}ed message:") print(translated) diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index ce490fd98524..b9af23dc8b00 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -15,7 +15,7 @@ def __repr__(self): if self.left is None and self.right is None: 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: diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index 7ad3e5540479..a6d476eb7320 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -96,7 +96,7 @@ def reset(): # Pulling Data (Output) while inp in ("e", "E"): - print("%s" % format(pull(), "#04x")) + print(f"{format(pull(), '#04x')}") print(buffer_space) print(params_space) inp = input("(e)exit? ").strip() diff --git a/machine_learning/gradient_boosting_regressor.py b/machine_learning/gradient_boosting_regressor.py index 0aa0e7a10ac5..c73e30680a67 100644 --- a/machine_learning/gradient_boosting_regressor.py +++ b/machine_learning/gradient_boosting_regressor.py @@ -47,9 +47,9 @@ def main(): y_pred = model.predict(X_test) # 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 - 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 fig, ax = plt.subplots() diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 10c9374d8492..60450b7f8493 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -164,9 +164,7 @@ def kmeans( num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( - " {:5d} elements changed their cluster assignment.".format( - num_changed - ) + f" {num_changed:5d} elements changed their cluster assignment." ) # Record heterogeneity convergence metric diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index b0bbc7b904c3..85fdfb0005ac 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -99,7 +99,7 @@ def main(): len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): - print("%.5f" % (theta[0, i])) + print(f"{theta[0, i]:.5f}") if __name__ == "__main__": diff --git a/matrix/sherman_morrison.py b/matrix/sherman_morrison.py index 3466b3d4a01f..63783c8b40fc 100644 --- a/matrix/sherman_morrison.py +++ b/matrix/sherman_morrison.py @@ -256,7 +256,7 @@ def test1(): v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") - print("uv^T is %s" % (u * v.transpose())) + print(f"uv^T is {u * v.transpose()}") # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index d821488025ef..e3993efb4249 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -71,7 +71,7 @@ def save_model(self, save_path): with open(save_path, "wb") as f: pickle.dump(model_dic, f) - print("Model saved: %s" % save_path) + print(f"Model saved: {save_path}") @classmethod def ReadModel(cls, model_path): @@ -303,7 +303,7 @@ def draw_error(): plt.show() print("------------------Training Complished---------------------") - print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse)) + print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}")) if draw_e: draw_error() return mse diff --git a/other/scoring_algorithm.py b/other/scoring_algorithm.py index cc1744012671..aecd19c55927 100644 --- a/other/scoring_algorithm.py +++ b/other/scoring_algorithm.py @@ -69,7 +69,7 @@ def procentual_proximity( # weight not 0 or 1 else: - raise ValueError("Invalid weight of %f provided" % (weight)) + raise ValueError(f"Invalid weight of {weight:f} provided") score_lists.append(score) diff --git a/scheduling/shortest_job_first.py b/scheduling/shortest_job_first.py index 9372e9dbc3f4..b3f81bfd10e7 100644 --- a/scheduling/shortest_job_first.py +++ b/scheduling/shortest_job_first.py @@ -111,7 +111,7 @@ def calculate_average_times( for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_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) diff --git a/searches/binary_tree_traversal.py b/searches/binary_tree_traversal.py index f919a2962354..033db83d789e 100644 --- a/searches/binary_tree_traversal.py +++ b/searches/binary_tree_traversal.py @@ -25,14 +25,14 @@ def build_tree(): q.put(tree_node) while not q.empty(): 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" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = 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" if check == "n": return tree_node diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index 147bc6fc740a..089c2532f900 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -31,28 +31,28 @@ def compute_transform_tables( for i in range(1, len_source_seq + 1): 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): 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 j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: 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: 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]: 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]: 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 From 5c1820bf9ac7d241330781d4a977b994fb90284c Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Thu, 7 Jul 2022 15:32:49 +0530 Subject: [PATCH 3/8] Update rsa_key_generator.py --- ciphers/rsa_key_generator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index 2e56b1614781..f4f3039f0a2e 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -34,8 +34,8 @@ def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]: def makeKeyFiles(name: str, keySize: int) -> None: - if os.path.exists(f"{name}_pubkey.txt") or os.path.exists( - f"{name}_privkey.txt" + if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( + "%s_privkey.txt" % (name) ): print("\nWARNING:") print( From 6da8c3fd38d86bb197973f8a36fd20a7295cbff2 Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Thu, 7 Jul 2022 15:57:31 +0530 Subject: [PATCH 4/8] Update rsa_key_generator.py --- ciphers/rsa_key_generator.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index f4f3039f0a2e..d983c14f1d7e 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -34,9 +34,7 @@ def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]: def makeKeyFiles(name: str, keySize: int) -> None: - if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( - "%s_privkey.txt" % (name) - ): + if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' From 1ac24382aacf29c06fdd5a25a16e56519e66bdc6 Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Thu, 7 Jul 2022 19:31:55 +0530 Subject: [PATCH 5/8] Update elgamal_key_generator.py --- ciphers/elgamal_key_generator.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ciphers/elgamal_key_generator.py b/ciphers/elgamal_key_generator.py index 93aabac3b56c..485b77595c7c 100644 --- a/ciphers/elgamal_key_generator.py +++ b/ciphers/elgamal_key_generator.py @@ -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: - if os.path.exists(f"{name}_pubkey.txt") or os.path.exists( - f"{name}_privkey.txt" - ): + if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' From a5b1b23c0f526fbf97466c177ac31bd3d6b99c7f Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Thu, 7 Jul 2022 19:54:29 +0530 Subject: [PATCH 6/8] 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. --- other/lru_cache.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/other/lru_cache.py b/other/lru_cache.py index 2c25a0855632..305ca0f96a2a 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -21,7 +21,11 @@ def __init__(self, key: T | None, val: U | None): self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: - return f"Node: key: {self.key}, val: {self.val}, has next: {self.next is not None}, has prev: {self.prev is not None}" + key_str = f"key: {self.key}" + val_str = f"val: {self.val}" + next_str = f"next: {self.next is not None}" + prev_str = f"prev: {self.prev is not None}" + return f"Node: {key_str}, {val_str}, has {next_str}, has {prev_str}" class DoubleLinkedList(Generic[T, U]): From 0735dc88de452da5664078d2964e968cd6b50d57 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Thu, 7 Jul 2022 16:26:36 +0200 Subject: [PATCH 7/8] Update lru_cache.py --- other/lru_cache.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/other/lru_cache.py b/other/lru_cache.py index 305ca0f96a2a..d7b056785468 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -21,11 +21,10 @@ def __init__(self, key: T | None, val: U | None): self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: - key_str = f"key: {self.key}" - val_str = f"val: {self.val}" - next_str = f"next: {self.next is not None}" - prev_str = f"prev: {self.prev is not None}" - return f"Node: {key_str}, {val_str}, has {next_str}, has {prev_str}" + return ( + f"Node: key: {self.key}, val: {self.val}, " + f"has next: {bool(self.next)}, has prev: {bool(self.prev}" + ) class DoubleLinkedList(Generic[T, U]): From 86cc9b08a0ac68a9aa13a7c7193326e9d984483c Mon Sep 17 00:00:00 2001 From: Vardhaman <83634399+cyai@users.noreply.github.com> Date: Thu, 7 Jul 2022 19:59:58 +0530 Subject: [PATCH 8/8] Update lru_cache.py --- other/lru_cache.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/other/lru_cache.py b/other/lru_cache.py index d7b056785468..834ea52a95e1 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -23,7 +23,7 @@ def __init__(self, key: T | None, val: U | None): def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, " - f"has next: {bool(self.next)}, has prev: {bool(self.prev}" + f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" )