Skip to content

Commit

Permalink
Improved readability (TheAlgorithms#1615)
Browse files Browse the repository at this point in the history
* improved readability

* further readability improvements

* removed csv file and added f
  • Loading branch information
GeorgeChara authored and cclauss committed Dec 7, 2019
1 parent 938dd0b commit 9eb50cc
Show file tree
Hide file tree
Showing 21 changed files with 44 additions and 50 deletions.
10 changes: 5 additions & 5 deletions arithmetic_analysis/newton_forward_interpolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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([])
Expand All @@ -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
Expand All @@ -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__":
Expand Down
2 changes: 1 addition & 1 deletion ciphers/trafid_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
2 changes: 1 addition & 1 deletion data_structures/linked_list/doubly_linked_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,4 @@ def __init__(self, x):
self.value = x

def displayLink(self):
print("{}".format(self.value), end=" ")
print(f"{self.value}", end=" ")
14 changes: 7 additions & 7 deletions divide_and_conquer/convex_hull.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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.")
Expand Down
4 changes: 2 additions & 2 deletions dynamic_programming/knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 5 additions & 5 deletions graphs/dijkstra_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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="")

Expand Down
2 changes: 1 addition & 1 deletion graphs/edmonds_karp_multiple_source_and_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
6 changes: 2 additions & 4 deletions graphs/page_rank.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions machine_learning/knn_sklearn.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 4 additions & 4 deletions machine_learning/linear_discriminant_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
8 changes: 3 additions & 5 deletions machine_learning/sequential_minimum_optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion maths/binary_exponentiation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
2 changes: 1 addition & 1 deletion maths/simpson_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
2 changes: 1 addition & 1 deletion maths/trapezoidal_rule.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
4 changes: 1 addition & 3 deletions neural_network/input_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion searches/binary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
2 changes: 1 addition & 1 deletion searches/interpolation_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
2 changes: 1 addition & 1 deletion searches/linear_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
2 changes: 1 addition & 1 deletion searches/sentinel_linear_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
2 changes: 1 addition & 1 deletion searches/tabu_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__":
Expand Down
4 changes: 2 additions & 2 deletions searches/ternary_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

0 comments on commit 9eb50cc

Please sign in to comment.