diff --git a/ciphers/elgamal_key_generator.py b/ciphers/elgamal_key_generator.py index f557b0e0d..485b77595 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("%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' @@ -50,14 +48,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 5bb9f9916..c6bfaa0fb 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 584066d89..d983c14f1 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' @@ -46,12 +44,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 589bb8cb5..ed9923a6b 100644 --- a/ciphers/transposition_cipher.py +++ b/ciphers/transposition_cipher.py @@ -10,7 +10,7 @@ text. The type of transposition cipher demonstrated under is the ROUTE cipher. 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 b91c73c9f..926a1b36a 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 d97a96949..2e3987708 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 ce490fd98..b9af23dc8 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -15,7 +15,7 @@ class Node: 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 7ad3e5540..a6d476eb7 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -96,7 +96,7 @@ if __name__ == "__main__": # 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 0aa0e7a10..c73e30680 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 10c9374d8..60450b7f8 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 b0bbc7b90..85fdfb000 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 3466b3d4a..63783c8b4 100644 --- a/matrix/sherman_morrison.py +++ b/matrix/sherman_morrison.py @@ -256,7 +256,7 @@ if __name__ == "__main__": 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 d82148802..e3993efb4 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -71,7 +71,7 @@ class CNN: 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 @@ class CNN: 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/lru_cache.py b/other/lru_cache.py index 98051f89d..834ea52a9 100644 --- a/other/lru_cache.py +++ b/other/lru_cache.py @@ -21,8 +21,9 @@ class DoubleLinkedListNode(Generic[T, U]): 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}, " + f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" ) diff --git a/other/scoring_algorithm.py b/other/scoring_algorithm.py index cc1744012..aecd19c55 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 9372e9dbc..b3f81bfd1 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 f919a2962..033db83d7 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 147bc6fc7..089c2532f 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