Skip to content

Commit 9eb50cc

Browse files
GeorgeCharacclauss
authored andcommitted
Improved readability (TheAlgorithms#1615)
* improved readability * further readability improvements * removed csv file and added f
1 parent 938dd0b commit 9eb50cc

21 files changed

+44
-50
lines changed

arithmetic_analysis/newton_forward_interpolation.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def ucal(u, p):
1919

2020

2121
def main():
22-
n = int(input("enter the numbers of values"))
22+
n = int(input("enter the numbers of values: "))
2323
y = []
2424
for i in range(n):
2525
y.append([])
@@ -28,14 +28,14 @@ def main():
2828
y[i].append(j)
2929
y[i][j] = 0
3030

31-
print("enter the values of parameters in a list")
31+
print("enter the values of parameters in a list: ")
3232
x = list(map(int, input().split()))
3333

34-
print("enter the values of corresponding parameters")
34+
print("enter the values of corresponding parameters: ")
3535
for i in range(n):
3636
y[i][0] = float(input())
3737

38-
value = int(input("enter the value to interpolate"))
38+
value = int(input("enter the value to interpolate: "))
3939
u = (value - x[0]) / (x[1] - x[0])
4040

4141
# for calculating forward difference table
@@ -48,7 +48,7 @@ def main():
4848
for i in range(1, n):
4949
summ += (ucal(u, i) * y[0][i]) / math.factorial(i)
5050

51-
print("the value at {} is {}".format(value, summ))
51+
print(f"the value at {value} is {summ}")
5252

5353

5454
if __name__ == "__main__":

ciphers/trafid_cipher.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,4 @@ def decryptMessage(message, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period=5):
117117
msg = "DEFEND THE EAST WALL OF THE CASTLE."
118118
encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
119119
decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
120-
print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted))
120+
print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")

data_structures/linked_list/doubly_linked_list.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,4 +76,4 @@ def __init__(self, x):
7676
self.value = x
7777

7878
def displayLink(self):
79-
print("{}".format(self.value), end=" ")
79+
print(f"{self.value}", end=" ")

divide_and_conquer/convex_hull.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def __init__(self, x, y):
5050
except ValueError as e:
5151
e.args = (
5252
"x and y must be both numeric types "
53-
"but got {}, {} instead".format(type(x), type(y)),
53+
f"but got {type(x)}, {type(y)} instead"
5454
)
5555
raise
5656

@@ -88,7 +88,7 @@ def __le__(self, other):
8888
return False
8989

9090
def __repr__(self):
91-
return "({}, {})".format(self.x, self.y)
91+
return f"({self.x}, {self.y})"
9292

9393
def __hash__(self):
9494
return hash(self.x)
@@ -136,8 +136,8 @@ def _construct_points(list_of_tuples):
136136
points.append(Point(p[0], p[1]))
137137
except (IndexError, TypeError):
138138
print(
139-
"Ignoring deformed point {}. All points"
140-
" must have at least 2 coordinates.".format(p)
139+
f"Ignoring deformed point {p}. All points"
140+
" must have at least 2 coordinates."
141141
)
142142
return points
143143

@@ -184,7 +184,7 @@ def _validate_input(points):
184184
"""
185185

186186
if not points:
187-
raise ValueError("Expecting a list of points but got {}".format(points))
187+
raise ValueError(f"Expecting a list of points but got {points}")
188188

189189
if isinstance(points, set):
190190
points = list(points)
@@ -196,12 +196,12 @@ def _validate_input(points):
196196
else:
197197
raise ValueError(
198198
"Expecting an iterable of type Point, list or tuple. "
199-
"Found objects of type {} instead".format(type(points[0]))
199+
f"Found objects of type {type(points[0])} instead"
200200
)
201201
elif not hasattr(points, "__iter__"):
202202
raise ValueError(
203203
"Expecting an iterable object "
204-
"but got an non-iterable type {}".format(points)
204+
f"but got an non-iterable type {points}"
205205
)
206206
except TypeError as e:
207207
print("Expecting an iterable of type Point, list or tuple.")

dynamic_programming/knapsack.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,13 +81,13 @@ def knapsack_with_example_solution(W: int, wt: list, val: list):
8181
raise ValueError(
8282
"The number of weights must be the "
8383
"same as the number of values.\nBut "
84-
"got {} weights and {} values".format(num_items, len(val))
84+
f"got {num_items} weights and {len(val)} values"
8585
)
8686
for i in range(num_items):
8787
if not isinstance(wt[i], int):
8888
raise TypeError(
8989
"All weights must be integers but "
90-
"got weight of type {} at index {}".format(type(wt[i]), i)
90+
f"got weight of type {type(wt[i])} at index {i}"
9191
)
9292

9393
optimal_val, dp_table = knapsack(W, wt, val, num_items)

graphs/dijkstra_algorithm.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def show_graph(self):
106106
print(
107107
u,
108108
"->",
109-
" -> ".join(str("{}({})".format(v, w)) for v, w in self.adjList[u]),
109+
" -> ".join(str(f"{v}({w})") for v, w in self.adjList[u]),
110110
)
111111

112112
def dijkstra(self, src):
@@ -139,9 +139,9 @@ def dijkstra(self, src):
139139
self.show_distances(src)
140140

141141
def show_distances(self, src):
142-
print("Distance from node: {}".format(src))
142+
print(f"Distance from node: {src}")
143143
for u in range(self.num_nodes):
144-
print("Node {} has distance: {}".format(u, self.dist[u]))
144+
print(f"Node {u} has distance: {self.dist[u]}")
145145

146146
def show_path(self, src, dest):
147147
# To show the shortest path from src to dest
@@ -161,9 +161,9 @@ def show_path(self, src, dest):
161161
path.append(src)
162162
path.reverse()
163163

164-
print("----Path to reach {} from {}----".format(dest, src))
164+
print(f"----Path to reach {dest} from {src}----")
165165
for u in path:
166-
print("{}".format(u), end=" ")
166+
print(f"{u}", end=" ")
167167
if u != dest:
168168
print("-> ", end="")
169169

graphs/edmonds_karp_multiple_source_and_sink.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,4 +190,4 @@ def relabel(self, vertexIndex):
190190
# and calculate
191191
maximumFlow = flowNetwork.findMaximumFlow()
192192

193-
print("maximum flow is {}".format(maximumFlow))
193+
print(f"maximum flow is {maximumFlow}")

graphs/page_rank.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@ def add_outbound(self, node):
2727
self.outbound.append(node)
2828

2929
def __repr__(self):
30-
return "Node {}: Inbound: {} ; Outbound: {}".format(
31-
self.name, self.inbound, self.outbound
32-
)
30+
return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}"
3331

3432

3533
def page_rank(nodes, limit=3, d=0.85):
@@ -42,7 +40,7 @@ def page_rank(nodes, limit=3, d=0.85):
4240
outbounds[node.name] = len(node.outbound)
4341

4442
for i in range(limit):
45-
print("======= Iteration {} =======".format(i + 1))
43+
print(f"======= Iteration {i + 1} =======")
4644
for j, node in enumerate(nodes):
4745
ranks[node.name] = (1 - d) + d * sum(
4846
[ranks[ib] / outbounds[ib] for ib in node.inbound]

machine_learning/knn_sklearn.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
iris.keys()
88

99

10-
print("Target names: \n {} ".format(iris.target_names))
11-
print("\n Features: \n {}".format(iris.feature_names))
10+
print(f"Target names: \n {iris.target_names} ")
11+
print(f"\n Features: \n {iris.feature_names}")
1212

1313
# Train set e Test set
1414
X_train, X_test, y_train, y_test = train_test_split(

machine_learning/linear_discriminant_analysis.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,8 +174,8 @@ def accuracy(actual_y: list, predicted_y: list) -> float:
174174
def main():
175175
""" This function starts execution phase """
176176
while True:
177-
print(" Linear Discriminant Analysis ".center(100, "*"))
178-
print("*" * 100, "\n")
177+
print(" Linear Discriminant Analysis ".center(50, "*"))
178+
print("*" * 50, "\n")
179179
print("First of all we should specify the number of classes that")
180180
print("we want to generate as training dataset")
181181
# Trying to get number of classes
@@ -239,7 +239,7 @@ def main():
239239
else:
240240
print(
241241
f"Your entered value is {user_count}, Number of "
242-
f"instances should be positive!"
242+
"instances should be positive!"
243243
)
244244
continue
245245
except ValueError:
@@ -302,7 +302,7 @@ def main():
302302
# for loop iterates over number of elements in 'probabilities' list and print
303303
# out them in separated line
304304
for i, probability in enumerate(probabilities, 1):
305-
print("Probability of class_{} is: {}".format(i, probability))
305+
print(f"Probability of class_{i} is: {probability}")
306306
print("-" * 100)
307307

308308
# Calculating the values of variance for each class

0 commit comments

Comments
 (0)