mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Improved readability (#1615)
* improved readability * further readability improvements * removed csv file and added f
This commit is contained in:
parent
938dd0bbb5
commit
9eb50cc223
|
@ -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__":
|
||||
|
|
|
@ -117,4 +117,4 @@ if __name__ == "__main__":
|
|||
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}")
|
||||
|
|
|
@ -76,4 +76,4 @@ class Link:
|
|||
self.value = x
|
||||
|
||||
def displayLink(self):
|
||||
print("{}".format(self.value), end=" ")
|
||||
print(f"{self.value}", end=" ")
|
||||
|
|
|
@ -50,7 +50,7 @@ class Point:
|
|||
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 @@ class Point:
|
|||
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.")
|
||||
|
|
|
@ -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)
|
||||
|
|
|
@ -106,7 +106,7 @@ class Graph:
|
|||
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 @@ class Graph:
|
|||
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 @@ class Graph:
|
|||
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="")
|
||||
|
||||
|
|
|
@ -190,4 +190,4 @@ if __name__ == "__main__":
|
|||
# and calculate
|
||||
maximumFlow = flowNetwork.findMaximumFlow()
|
||||
|
||||
print("maximum flow is {}".format(maximumFlow))
|
||||
print(f"maximum flow is {maximumFlow}")
|
||||
|
|
|
@ -27,9 +27,7 @@ class 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]
|
||||
|
|
|
@ -7,8 +7,8 @@ iris = load_iris()
|
|||
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(
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -446,7 +446,7 @@ def count_time(func):
|
|||
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():
|
||||
|
|
|
@ -25,4 +25,4 @@ if __name__ == "__main__":
|
|||
print("Invalid literal for integer")
|
||||
|
||||
RESULT = binary_exponentiation(BASE, POWER)
|
||||
print("{}^({}) : {}".format(BASE, POWER, RESULT))
|
||||
print(f"{BASE}^({POWER}) : {RESULT}")
|
||||
|
|
|
@ -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__":
|
||||
|
|
|
@ -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__":
|
||||
|
|
|
@ -331,9 +331,7 @@ def read_data_sets(
|
|||
|
||||
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]
|
||||
|
|
|
@ -152,6 +152,6 @@ if __name__ == "__main__":
|
|||
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")
|
||||
|
|
|
@ -135,6 +135,6 @@ if __name__ == "__main__":
|
|||
|
||||
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")
|
||||
|
|
|
@ -45,6 +45,6 @@ if __name__ == "__main__":
|
|||
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")
|
||||
|
|
|
@ -53,6 +53,6 @@ if __name__ == "__main__":
|
|||
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")
|
||||
|
|
|
@ -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__":
|
||||
|
|
|
@ -97,7 +97,7 @@ if __name__ == "__main__":
|
|||
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")
|
||||
|
|
Loading…
Reference in New Issue
Block a user