Skip to content

Improved readability #1615

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 7, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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})"
Copy link
Member

@cclauss cclauss Dec 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return f"Point({self.x}, {self.y})"

repr() should return a string that would yield an object with the same value when passed to eval() https://docs.python.org/3/library/functions.html#repr


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("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
Loading