diff --git a/arithmetic_analysis/newton_forward_interpolation.py b/arithmetic_analysis/newton_forward_interpolation.py index 09adb5113f82..d91b9709f3d6 100644 --- a/arithmetic_analysis/newton_forward_interpolation.py +++ b/arithmetic_analysis/newton_forward_interpolation.py @@ -19,7 +19,7 @@ def ucal(u, p): def main(): - n = int(input("enter the numbers of values")) + n = int(input("enter the numbers of values: ")) y = [] for i in range(n): y.append([]) @@ -28,14 +28,14 @@ def main(): y[i].append(j) y[i][j] = 0 - print("enter the values of parameters in a list") + print("enter the values of parameters in a list: ") x = list(map(int, input().split())) - print("enter the values of corresponding parameters") + print("enter the values of corresponding parameters: ") for i in range(n): y[i][0] = float(input()) - value = int(input("enter the value to interpolate")) + value = int(input("enter the value to interpolate: ")) u = (value - x[0]) / (x[1] - x[0]) # for calculating forward difference table @@ -48,7 +48,7 @@ def main(): for i in range(1, n): summ += (ucal(u, i) * y[0][i]) / math.factorial(i) - print("the value at {} is {}".format(value, summ)) + print(f"the value at {value} is {summ}") if __name__ == "__main__": diff --git a/ciphers/trafid_cipher.py b/ciphers/trafid_cipher.py index 0add9ee74beb..f1c954b5c34f 100644 --- a/ciphers/trafid_cipher.py +++ b/ciphers/trafid_cipher.py @@ -117,4 +117,4 @@ def decryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5): msg = "DEFEND THE EAST WALL OF THE CASTLE." encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") - print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted)) + print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}") diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 2a95a004587c..2864356c1d19 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -76,4 +76,4 @@ def __init__(self, x): self.value = x def displayLink(self): - print("{}".format(self.value), end=" ") + print(f"{self.value}", end=" ") diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index bd88256ab01c..21463e62197d 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -50,7 +50,7 @@ def __init__(self, x, y): except ValueError as e: e.args = ( "x and y must be both numeric types " - "but got {}, {} instead".format(type(x), type(y)), + f"but got {type(x)}, {type(y)} instead" ) raise @@ -88,7 +88,7 @@ def __le__(self, other): return False def __repr__(self): - return "({}, {})".format(self.x, self.y) + return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) @@ -136,8 +136,8 @@ def _construct_points(list_of_tuples): points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( - "Ignoring deformed point {}. All points" - " must have at least 2 coordinates.".format(p) + f"Ignoring deformed point {p}. All points" + " must have at least 2 coordinates." ) return points @@ -184,7 +184,7 @@ def _validate_input(points): """ if not points: - raise ValueError("Expecting a list of points but got {}".format(points)) + raise ValueError(f"Expecting a list of points but got {points}") if isinstance(points, set): points = list(points) @@ -196,12 +196,12 @@ def _validate_input(points): else: raise ValueError( "Expecting an iterable of type Point, list or tuple. " - "Found objects of type {} instead".format(type(points[0])) + f"Found objects of type {type(points[0])} instead" ) elif not hasattr(points, "__iter__"): raise ValueError( "Expecting an iterable object " - "but got an non-iterable type {}".format(points) + f"but got an non-iterable type {points}" ) except TypeError as e: print("Expecting an iterable of type Point, list or tuple.") diff --git a/dynamic_programming/knapsack.py b/dynamic_programming/knapsack.py index e71e3892e8cc..aefaa6bade96 100644 --- a/dynamic_programming/knapsack.py +++ b/dynamic_programming/knapsack.py @@ -81,13 +81,13 @@ def knapsack_with_example_solution(W: int, wt: list, val: list): raise ValueError( "The number of weights must be the " "same as the number of values.\nBut " - "got {} weights and {} values".format(num_items, len(val)) + f"got {num_items} weights and {len(val)} values" ) for i in range(num_items): if not isinstance(wt[i], int): raise TypeError( "All weights must be integers but " - "got weight of type {} at index {}".format(type(wt[i]), i) + f"got weight of type {type(wt[i])} at index {i}" ) optimal_val, dp_table = knapsack(W, wt, val, num_items) diff --git a/graphs/dijkstra_algorithm.py b/graphs/dijkstra_algorithm.py index 9304a83148f3..57733eb5106d 100644 --- a/graphs/dijkstra_algorithm.py +++ b/graphs/dijkstra_algorithm.py @@ -106,7 +106,7 @@ def show_graph(self): print( u, "->", - " -> ".join(str("{}({})".format(v, w)) for v, w in self.adjList[u]), + " -> ".join(str(f"{v}({w})") for v, w in self.adjList[u]), ) def dijkstra(self, src): @@ -139,9 +139,9 @@ def dijkstra(self, src): self.show_distances(src) def show_distances(self, src): - print("Distance from node: {}".format(src)) + print(f"Distance from node: {src}") for u in range(self.num_nodes): - print("Node {} has distance: {}".format(u, self.dist[u])) + print(f"Node {u} has distance: {self.dist[u]}") def show_path(self, src, dest): # To show the shortest path from src to dest @@ -161,9 +161,9 @@ def show_path(self, src, dest): path.append(src) path.reverse() - print("----Path to reach {} from {}----".format(dest, src)) + print(f"----Path to reach {dest} from {src}----") for u in path: - print("{}".format(u), end=" ") + print(f"{u}", end=" ") if u != dest: print("-> ", end="") diff --git a/graphs/edmonds_karp_multiple_source_and_sink.py b/graphs/edmonds_karp_multiple_source_and_sink.py index 6334f05c50bd..eb6ec739ba00 100644 --- a/graphs/edmonds_karp_multiple_source_and_sink.py +++ b/graphs/edmonds_karp_multiple_source_and_sink.py @@ -190,4 +190,4 @@ def relabel(self, vertexIndex): # and calculate maximumFlow = flowNetwork.findMaximumFlow() - print("maximum flow is {}".format(maximumFlow)) + print(f"maximum flow is {maximumFlow}") diff --git a/graphs/page_rank.py b/graphs/page_rank.py index 1e2c7d9aeb48..0f5129146ddf 100644 --- a/graphs/page_rank.py +++ b/graphs/page_rank.py @@ -27,9 +27,7 @@ def add_outbound(self, node): self.outbound.append(node) def __repr__(self): - return "Node {}: Inbound: {} ; Outbound: {}".format( - self.name, self.inbound, self.outbound - ) + return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}" def page_rank(nodes, limit=3, d=0.85): @@ -42,7 +40,7 @@ def page_rank(nodes, limit=3, d=0.85): outbounds[node.name] = len(node.outbound) for i in range(limit): - print("======= Iteration {} =======".format(i + 1)) + print(f"======= Iteration {i + 1} =======") for j, node in enumerate(nodes): ranks[node.name] = (1 - d) + d * sum( [ranks[ib] / outbounds[ib] for ib in node.inbound] diff --git a/machine_learning/knn_sklearn.py b/machine_learning/knn_sklearn.py index a371e30f5403..c36a530736cd 100644 --- a/machine_learning/knn_sklearn.py +++ b/machine_learning/knn_sklearn.py @@ -7,8 +7,8 @@ iris.keys() -print("Target names: \n {} ".format(iris.target_names)) -print("\n Features: \n {}".format(iris.feature_names)) +print(f"Target names: \n {iris.target_names} ") +print(f"\n Features: \n {iris.feature_names}") # Train set e Test set X_train, X_test, y_train, y_test = train_test_split( diff --git a/machine_learning/linear_discriminant_analysis.py b/machine_learning/linear_discriminant_analysis.py index 62dc34af6bbd..cc2f1dac7237 100644 --- a/machine_learning/linear_discriminant_analysis.py +++ b/machine_learning/linear_discriminant_analysis.py @@ -174,8 +174,8 @@ def accuracy(actual_y: list, predicted_y: list) -> float: def main(): """ This function starts execution phase """ while True: - print(" Linear Discriminant Analysis ".center(100, "*")) - print("*" * 100, "\n") + print(" Linear Discriminant Analysis ".center(50, "*")) + print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes @@ -239,7 +239,7 @@ def main(): else: print( f"Your entered value is {user_count}, Number of " - f"instances should be positive!" + "instances should be positive!" ) continue except ValueError: @@ -302,7 +302,7 @@ def main(): # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): - print("Probability of class_{} is: {}".format(i, probability)) + print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class diff --git a/machine_learning/sequential_minimum_optimization.py b/machine_learning/sequential_minimum_optimization.py index 1d4e4a276bc1..cb859602b29f 100644 --- a/machine_learning/sequential_minimum_optimization.py +++ b/machine_learning/sequential_minimum_optimization.py @@ -446,7 +446,7 @@ def call_func(*args, **kwargs): start_time = time.time() func(*args, **kwargs) end_time = time.time() - print("smo algorithm cost {} seconds".format(end_time - start_time)) + print(f"smo algorithm cost {end_time - start_time} seconds") return call_func @@ -500,11 +500,9 @@ def test_cancel_data(): if test_tags[i] == predict[i]: score += 1 print( - "\r\nall: {}\r\nright: {}\r\nfalse: {}".format( - test_num, score, test_num - score - ) + f"\r\nall: {test_num}\r\nright: {score}\r\nfalse: {test_num - score}" ) - print("Rough Accuracy: {}".format(score / test_tags.shape[0])) + print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): diff --git a/maths/binary_exponentiation.py b/maths/binary_exponentiation.py index 57c4b8686f5c..8dda5245cf44 100644 --- a/maths/binary_exponentiation.py +++ b/maths/binary_exponentiation.py @@ -25,4 +25,4 @@ def binary_exponentiation(a, n): print("Invalid literal for integer") RESULT = binary_exponentiation(BASE, POWER) - print("{}^({}) : {}".format(BASE, POWER, RESULT)) + print(f"{BASE}^({POWER}) : {RESULT}") diff --git a/maths/simpson_rule.py b/maths/simpson_rule.py index f4620be8e70f..91098804395d 100644 --- a/maths/simpson_rule.py +++ b/maths/simpson_rule.py @@ -44,7 +44,7 @@ def main(): steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) - print("y = {0}".format(y)) + print(f"y = {y}") if __name__ == "__main__": diff --git a/maths/trapezoidal_rule.py b/maths/trapezoidal_rule.py index 0f321317614d..0f7dea6bf888 100644 --- a/maths/trapezoidal_rule.py +++ b/maths/trapezoidal_rule.py @@ -43,7 +43,7 @@ def main(): steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_1(boundary, steps) - print("y = {0}".format(y)) + print(f"y = {y}") if __name__ == "__main__": diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 5e6c433aa97d..ea826be6cd84 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -331,9 +331,7 @@ def fake(): if not 0 <= validation_size <= len(train_images): raise ValueError( - "Validation size should be between 0 and {}. Received: {}.".format( - len(train_images), validation_size - ) + f"Validation size should be between 0 and {len(train_images)}. Received: {validation_size}." ) validation_images = train_images[:validation_size] diff --git a/searches/binary_search.py b/searches/binary_search.py index 76a50560e943..ff959c6cf2e3 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -152,6 +152,6 @@ def __assert_sorted(collection): target = int(target_input) result = binary_search(collection, target) if result is not None: - print("{} found at positions: {}".format(target, result)) + print(f"{target} found at positions: {result}") else: print("Not found") diff --git a/searches/interpolation_search.py b/searches/interpolation_search.py index dffaf8d26084..fd26ae0c64ce 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -135,6 +135,6 @@ def __assert_sorted(collection): result = interpolation_search(collection, target) if result is not None: - print("{} found at positions: {}".format(target, result)) + print(f"{target} found at positions: {result}") else: print("Not found") diff --git a/searches/linear_search.py b/searches/linear_search.py index ab20f3527bb3..b6f52ca4857f 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -45,6 +45,6 @@ def linear_search(sequence, target): target = int(target_input) result = linear_search(sequence, target) if result is not None: - print("{} found at positions: {}".format(target, result)) + print(f"{target} found at positions: {result}") else: print("Not found") diff --git a/searches/sentinel_linear_search.py b/searches/sentinel_linear_search.py index 6c4da9b21189..5650151b1d2f 100644 --- a/searches/sentinel_linear_search.py +++ b/searches/sentinel_linear_search.py @@ -53,6 +53,6 @@ def sentinel_linear_search(sequence, target): target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: - print("{} found at positions: {}".format(target, result)) + print(f"{target} found at positions: {result}") else: print("Not found") diff --git a/searches/tabu_search.py b/searches/tabu_search.py index 9a1478244503..52086f1235ab 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -254,7 +254,7 @@ def main(args=None): args.Size, ) - print("Best solution: {0}, with total distance: {1}.".format(best_sol, best_cost)) + print(f"Best solution: {best_sol}, with total distance: {best_cost}.") if __name__ == "__main__": diff --git a/searches/ternary_search.py b/searches/ternary_search.py index 43407b7e5538..5ecc47644248 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -97,7 +97,7 @@ def __assert_sorted(collection): result2 = rec_ternary_search(0, len(collection) - 1, collection, target) if result2 is not None: - print("Iterative search: {} found at positions: {}".format(target, result1)) - print("Recursive search: {} found at positions: {}".format(target, result2)) + print(f"Iterative search: {target} found at positions: {result1}") + print(f"Recursive search: {target} found at positions: {result2}") else: print("Not found")