Improved readability (#1615)

* improved readability

* further readability improvements

* removed csv file and added f
This commit is contained in:
GeorgeChambi 2019-12-07 05:39:59 +00:00 committed by Christian Clauss
parent 938dd0bbb5
commit 9eb50cc223
21 changed files with 44 additions and 50 deletions

View File

@ -19,7 +19,7 @@ def ucal(u, p):
def main(): def main():
n = int(input("enter the numbers of values")) n = int(input("enter the numbers of values: "))
y = [] y = []
for i in range(n): for i in range(n):
y.append([]) y.append([])
@ -28,14 +28,14 @@ def main():
y[i].append(j) y[i].append(j)
y[i][j] = 0 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())) 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): for i in range(n):
y[i][0] = float(input()) 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]) u = (value - x[0]) / (x[1] - x[0])
# for calculating forward difference table # for calculating forward difference table
@ -48,7 +48,7 @@ def main():
for i in range(1, n): for i in range(1, n):
summ += (ucal(u, i) * y[0][i]) / math.factorial(i) 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__": if __name__ == "__main__":

View File

@ -117,4 +117,4 @@ if __name__ == "__main__":
msg = "DEFEND THE EAST WALL OF THE CASTLE." msg = "DEFEND THE EAST WALL OF THE CASTLE."
encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") encrypted = encryptMessage(msg, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ") decrypted = decryptMessage(encrypted, "EPSDUCVWYM.ZLKXNBTFGORIJHAQ")
print("Encrypted: {}\nDecrypted: {}".format(encrypted, decrypted)) print(f"Encrypted: {encrypted}\nDecrypted: {decrypted}")

View File

@ -76,4 +76,4 @@ class Link:
self.value = x self.value = x
def displayLink(self): def displayLink(self):
print("{}".format(self.value), end=" ") print(f"{self.value}", end=" ")

View File

@ -50,7 +50,7 @@ class Point:
except ValueError as e: except ValueError as e:
e.args = ( e.args = (
"x and y must be both numeric types " "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 raise
@ -88,7 +88,7 @@ class Point:
return False return False
def __repr__(self): def __repr__(self):
return "({}, {})".format(self.x, self.y) return f"({self.x}, {self.y})"
def __hash__(self): def __hash__(self):
return hash(self.x) return hash(self.x)
@ -136,8 +136,8 @@ def _construct_points(list_of_tuples):
points.append(Point(p[0], p[1])) points.append(Point(p[0], p[1]))
except (IndexError, TypeError): except (IndexError, TypeError):
print( print(
"Ignoring deformed point {}. All points" f"Ignoring deformed point {p}. All points"
" must have at least 2 coordinates.".format(p) " must have at least 2 coordinates."
) )
return points return points
@ -184,7 +184,7 @@ def _validate_input(points):
""" """
if not 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): if isinstance(points, set):
points = list(points) points = list(points)
@ -196,12 +196,12 @@ def _validate_input(points):
else: else:
raise ValueError( raise ValueError(
"Expecting an iterable of type Point, list or tuple. " "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__"): elif not hasattr(points, "__iter__"):
raise ValueError( raise ValueError(
"Expecting an iterable object " "Expecting an iterable object "
"but got an non-iterable type {}".format(points) f"but got an non-iterable type {points}"
) )
except TypeError as e: except TypeError as e:
print("Expecting an iterable of type Point, list or tuple.") print("Expecting an iterable of type Point, list or tuple.")

View File

@ -81,13 +81,13 @@ def knapsack_with_example_solution(W: int, wt: list, val: list):
raise ValueError( raise ValueError(
"The number of weights must be the " "The number of weights must be the "
"same as the number of values.\nBut " "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): for i in range(num_items):
if not isinstance(wt[i], int): if not isinstance(wt[i], int):
raise TypeError( raise TypeError(
"All weights must be integers but " "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) optimal_val, dp_table = knapsack(W, wt, val, num_items)

View File

@ -106,7 +106,7 @@ class Graph:
print( print(
u, 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): def dijkstra(self, src):
@ -139,9 +139,9 @@ class Graph:
self.show_distances(src) self.show_distances(src)
def show_distances(self, 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): 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): def show_path(self, src, dest):
# To show the shortest path from src to dest # To show the shortest path from src to dest
@ -161,9 +161,9 @@ class Graph:
path.append(src) path.append(src)
path.reverse() path.reverse()
print("----Path to reach {} from {}----".format(dest, src)) print(f"----Path to reach {dest} from {src}----")
for u in path: for u in path:
print("{}".format(u), end=" ") print(f"{u}", end=" ")
if u != dest: if u != dest:
print("-> ", end="") print("-> ", end="")

View File

@ -190,4 +190,4 @@ if __name__ == "__main__":
# and calculate # and calculate
maximumFlow = flowNetwork.findMaximumFlow() maximumFlow = flowNetwork.findMaximumFlow()
print("maximum flow is {}".format(maximumFlow)) print(f"maximum flow is {maximumFlow}")

View File

@ -27,9 +27,7 @@ class Node:
self.outbound.append(node) self.outbound.append(node)
def __repr__(self): def __repr__(self):
return "Node {}: Inbound: {} ; Outbound: {}".format( return f"Node {self.name}: Inbound: {self.inbound} ; Outbound: {self.outbound}"
self.name, self.inbound, self.outbound
)
def page_rank(nodes, limit=3, d=0.85): 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) outbounds[node.name] = len(node.outbound)
for i in range(limit): for i in range(limit):
print("======= Iteration {} =======".format(i + 1)) print(f"======= Iteration {i + 1} =======")
for j, node in enumerate(nodes): for j, node in enumerate(nodes):
ranks[node.name] = (1 - d) + d * sum( ranks[node.name] = (1 - d) + d * sum(
[ranks[ib] / outbounds[ib] for ib in node.inbound] [ranks[ib] / outbounds[ib] for ib in node.inbound]

View File

@ -7,8 +7,8 @@ iris = load_iris()
iris.keys() iris.keys()
print("Target names: \n {} ".format(iris.target_names)) print(f"Target names: \n {iris.target_names} ")
print("\n Features: \n {}".format(iris.feature_names)) print(f"\n Features: \n {iris.feature_names}")
# Train set e Test set # Train set e Test set
X_train, X_test, y_train, y_test = train_test_split( X_train, X_test, y_train, y_test = train_test_split(

View File

@ -174,8 +174,8 @@ def accuracy(actual_y: list, predicted_y: list) -> float:
def main(): def main():
""" This function starts execution phase """ """ This function starts execution phase """
while True: while True:
print(" Linear Discriminant Analysis ".center(100, "*")) print(" Linear Discriminant Analysis ".center(50, "*"))
print("*" * 100, "\n") print("*" * 50, "\n")
print("First of all we should specify the number of classes that") print("First of all we should specify the number of classes that")
print("we want to generate as training dataset") print("we want to generate as training dataset")
# Trying to get number of classes # Trying to get number of classes
@ -239,7 +239,7 @@ def main():
else: else:
print( print(
f"Your entered value is {user_count}, Number of " f"Your entered value is {user_count}, Number of "
f"instances should be positive!" "instances should be positive!"
) )
continue continue
except ValueError: except ValueError:
@ -302,7 +302,7 @@ def main():
# for loop iterates over number of elements in 'probabilities' list and print # for loop iterates over number of elements in 'probabilities' list and print
# out them in separated line # out them in separated line
for i, probability in enumerate(probabilities, 1): 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) print("-" * 100)
# Calculating the values of variance for each class # Calculating the values of variance for each class

View File

@ -446,7 +446,7 @@ def count_time(func):
start_time = time.time() start_time = time.time()
func(*args, **kwargs) func(*args, **kwargs)
end_time = time.time() 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 return call_func
@ -500,11 +500,9 @@ def test_cancel_data():
if test_tags[i] == predict[i]: if test_tags[i] == predict[i]:
score += 1 score += 1
print( print(
"\r\nall: {}\r\nright: {}\r\nfalse: {}".format( f"\r\nall: {test_num}\r\nright: {score}\r\nfalse: {test_num - score}"
test_num, score, test_num - score
) )
) print(f"Rough Accuracy: {score / test_tags.shape[0]}")
print("Rough Accuracy: {}".format(score / test_tags.shape[0]))
def test_demonstration(): def test_demonstration():

View File

@ -25,4 +25,4 @@ if __name__ == "__main__":
print("Invalid literal for integer") print("Invalid literal for integer")
RESULT = binary_exponentiation(BASE, POWER) RESULT = binary_exponentiation(BASE, POWER)
print("{}^({}) : {}".format(BASE, POWER, RESULT)) print(f"{BASE}^({POWER}) : {RESULT}")

View File

@ -44,7 +44,7 @@ def main():
steps = 10.0 # define number of steps or resolution steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration boundary = [a, b] # define boundary of integration
y = method_2(boundary, steps) y = method_2(boundary, steps)
print("y = {0}".format(y)) print(f"y = {y}")
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -43,7 +43,7 @@ def main():
steps = 10.0 # define number of steps or resolution steps = 10.0 # define number of steps or resolution
boundary = [a, b] # define boundary of integration boundary = [a, b] # define boundary of integration
y = method_1(boundary, steps) y = method_1(boundary, steps)
print("y = {0}".format(y)) print(f"y = {y}")
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -331,9 +331,7 @@ def read_data_sets(
if not 0 <= validation_size <= len(train_images): if not 0 <= validation_size <= len(train_images):
raise ValueError( raise ValueError(
"Validation size should be between 0 and {}. Received: {}.".format( f"Validation size should be between 0 and {len(train_images)}. Received: {validation_size}."
len(train_images), validation_size
)
) )
validation_images = train_images[:validation_size] validation_images = train_images[:validation_size]

View File

@ -152,6 +152,6 @@ if __name__ == "__main__":
target = int(target_input) target = int(target_input)
result = binary_search(collection, target) result = binary_search(collection, target)
if result is not None: if result is not None:
print("{} found at positions: {}".format(target, result)) print(f"{target} found at positions: {result}")
else: else:
print("Not found") print("Not found")

View File

@ -135,6 +135,6 @@ if __name__ == "__main__":
result = interpolation_search(collection, target) result = interpolation_search(collection, target)
if result is not None: if result is not None:
print("{} found at positions: {}".format(target, result)) print(f"{target} found at positions: {result}")
else: else:
print("Not found") print("Not found")

View File

@ -45,6 +45,6 @@ if __name__ == "__main__":
target = int(target_input) target = int(target_input)
result = linear_search(sequence, target) result = linear_search(sequence, target)
if result is not None: if result is not None:
print("{} found at positions: {}".format(target, result)) print(f"{target} found at positions: {result}")
else: else:
print("Not found") print("Not found")

View File

@ -53,6 +53,6 @@ if __name__ == "__main__":
target = int(target_input) target = int(target_input)
result = sentinel_linear_search(sequence, target) result = sentinel_linear_search(sequence, target)
if result is not None: if result is not None:
print("{} found at positions: {}".format(target, result)) print(f"{target} found at positions: {result}")
else: else:
print("Not found") print("Not found")

View File

@ -254,7 +254,7 @@ def main(args=None):
args.Size, 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__": if __name__ == "__main__":

View File

@ -97,7 +97,7 @@ if __name__ == "__main__":
result2 = rec_ternary_search(0, len(collection) - 1, collection, target) result2 = rec_ternary_search(0, len(collection) - 1, collection, target)
if result2 is not None: if result2 is not None:
print("Iterative search: {} found at positions: {}".format(target, result1)) print(f"Iterative search: {target} found at positions: {result1}")
print("Recursive search: {} found at positions: {}".format(target, result2)) print(f"Recursive search: {target} found at positions: {result2}")
else: else:
print("Not found") print("Not found")