diff --git a/Graphs/Directed and Undirected (Weighted) Graph.py b/Graphs/Directed and Undirected (Weighted) Graph.py index 68977de..41bb1b3 100644 --- a/Graphs/Directed and Undirected (Weighted) Graph.py +++ b/Graphs/Directed and Undirected (Weighted) Graph.py @@ -35,12 +35,10 @@ def remove_pair(self, u, v): def dfs(self, s = -2, d = -1): if s == d: return [] - stack = [] - visited = [] if s == -2: s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] ss = s while True: @@ -59,15 +57,15 @@ def dfs(self, s = -2, d = -1): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return visited # c is the count of nodes you want and if you leave it or pass -1 to the funtion the count @@ -86,11 +84,10 @@ def fill_graph_randomly(self, c = -1): def bfs(self, s = -2): d = deque() - visited = [] if s == -2: s = list(self.graph.keys())[0] d.append(s) - visited.append(s) + visited = [s] while d: s = d.popleft() if len(self.graph[s]) != 0: @@ -111,12 +108,10 @@ def out_degree(self, u): return len(self.graph[u]) def topological_sort(self, s = -2): - stack = [] - visited = [] if s == -2: s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] ss = s sorted_nodes = [] @@ -132,23 +127,21 @@ def topological_sort(self, s = -2): break # check if all the children are visited - if s == ss : + if s == ss: sorted_nodes.append(stack.pop()) - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return sorted_nodes def cycle_nodes(self): - stack = [] - visited = [] s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] parent = -2 indirect_parents = [] ss = s @@ -161,7 +154,7 @@ def cycle_nodes(self): for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 - while True and l >= 0: + while l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break @@ -175,11 +168,11 @@ def cycle_nodes(self): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() on_the_way_back = True - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: on_the_way_back = False indirect_parents.append(parent) @@ -187,15 +180,13 @@ def cycle_nodes(self): s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return list(anticipating_nodes) def has_cycle(self): - stack = [] - visited = [] s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] parent = -2 indirect_parents = [] ss = s @@ -208,14 +199,11 @@ def has_cycle(self): for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 - while True and l >= 0: - if stack[l] == __[1]: - anticipating_nodes.add(__[1]) - break - else: + while l >= 0: + if stack[l] != __[1]: return True - anticipating_nodes.add(stack[l]) - l -= 1 + anticipating_nodes.add(__[1]) + break if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) @@ -223,11 +211,11 @@ def has_cycle(self): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() on_the_way_back = True - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: on_the_way_back = False indirect_parents.append(parent) @@ -235,7 +223,7 @@ def has_cycle(self): s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return False def dfs_time(self, s = -2, e = -1): @@ -291,12 +279,10 @@ def remove_pair(self, u, v): def dfs(self, s = -2, d = -1): if s == d: return [] - stack = [] - visited = [] if s == -2: s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] ss = s while True: @@ -315,15 +301,15 @@ def dfs(self, s = -2, d = -1): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return visited # c is the count of nodes you want and if you leave it or pass -1 to the funtion the count @@ -342,11 +328,10 @@ def fill_graph_randomly(self, c = -1): def bfs(self, s = -2): d = deque() - visited = [] if s == -2: s = list(self.graph.keys())[0] d.append(s) - visited.append(s) + visited = [s] while d: s = d.popleft() if len(self.graph[s]) != 0: @@ -359,11 +344,9 @@ def degree(self, u): return len(self.graph[u]) def cycle_nodes(self): - stack = [] - visited = [] s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] parent = -2 indirect_parents = [] ss = s @@ -376,7 +359,7 @@ def cycle_nodes(self): for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 - while True and l >= 0: + while l >= 0: if stack[l] == __[1]: anticipating_nodes.add(__[1]) break @@ -390,11 +373,11 @@ def cycle_nodes(self): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() on_the_way_back = True - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: on_the_way_back = False indirect_parents.append(parent) @@ -402,15 +385,13 @@ def cycle_nodes(self): s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return list(anticipating_nodes) def has_cycle(self): - stack = [] - visited = [] s = list(self.graph.keys())[0] - stack.append(s) - visited.append(s) + stack = [s] + visited = [s] parent = -2 indirect_parents = [] ss = s @@ -423,14 +404,11 @@ def has_cycle(self): for __ in self.graph[s]: if visited.count(__[1]) > 0 and __[1] != parent and indirect_parents.count(__[1]) > 0 and not on_the_way_back: l = len(stack) - 1 - while True and l >= 0: - if stack[l] == __[1]: - anticipating_nodes.add(__[1]) - break - else: + while l >= 0: + if stack[l] != __[1]: return True - anticipating_nodes.add(stack[l]) - l -= 1 + anticipating_nodes.add(__[1]) + break if visited.count(__[1]) < 1: stack.append(__[1]) visited.append(__[1]) @@ -438,11 +416,11 @@ def has_cycle(self): break # check if all the children are visited - if s == ss : + if s == ss: stack.pop() on_the_way_back = True - if len(stack) != 0: - s = stack[len(stack) - 1] + if stack: + s = stack[-1] else: on_the_way_back = False indirect_parents.append(parent) @@ -450,7 +428,7 @@ def has_cycle(self): s = ss # check if se have reached the starting point - if len(stack) == 0: + if not stack: return False def all_nodes(self): return list(self.graph) diff --git a/Graphs/a_star.py b/Graphs/a_star.py index 584222e..2105d82 100644 --- a/Graphs/a_star.py +++ b/Graphs/a_star.py @@ -18,7 +18,7 @@ cost = 1 #the cost map which pushes the path closer to the goal -heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))] +heuristic = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] for i in range(len(grid)): for j in range(len(grid[0])): heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1]) @@ -36,9 +36,9 @@ #function to search the path def search(grid,init,goal,cost,heuristic): - closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence grid + closed = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] closed[init[0]][init[1]] = 1 - action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action grid + action = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] x = init[0] y = init[1] @@ -50,7 +50,7 @@ def search(grid,init,goal,cost,heuristic): resign = False # flag set if we can't find expand while not found and not resign: - if len(cell) == 0: + if not cell: resign = True return "FAIL" else: @@ -62,7 +62,7 @@ def search(grid,init,goal,cost,heuristic): g = next[1] f = next[0] - + if x == goal[0] and y == goal[1]: found = True else: @@ -76,10 +76,9 @@ def search(grid,init,goal,cost,heuristic): cell.append([f2, g2, x2, y2]) closed[x2][y2] = 1 action[x2][y2] = i - invpath = [] x = goal[0] y = goal[1] - invpath.append([x, y])#we get the reverse path from here + invpath = [[x, y]] while x != init[0] or y != init[1]: x2 = x - delta[action[x][y]][0] y2 = y - delta[action[x][y]][1] @@ -87,13 +86,11 @@ def search(grid,init,goal,cost,heuristic): y = y2 invpath.append([x, y]) - path = [] - for i in range(len(invpath)): - path.append(invpath[len(invpath) - 1 - i]) + path = [invpath[len(invpath) - 1 - i] for i in range(len(invpath))] print("ACTION MAP") - for i in range(len(action)): - print(action[i]) - + for item in action: + print(item) + return path a = search(grid,init,goal,cost,heuristic) diff --git a/Graphs/basic_graphs.py b/Graphs/basic_graphs.py index 3b3abeb..a295c3d 100644 --- a/Graphs/basic_graphs.py +++ b/Graphs/basic_graphs.py @@ -13,11 +13,7 @@ # Accept No. of Nodes and edges n, m = map(int, raw_input().split(" ")) -# Initialising Dictionary of edges -g = {} -for i in xrange(n): - g[i + 1] = [] - +g = {i + 1: [] for i in xrange(n)} """ -------------------------------------------------------------------------------- Accepting edges of Unweighted Directed Graphs @@ -59,7 +55,7 @@ def dfs(G, s): - vis, S = set([s]), [s] + vis, S = {s}, [s] print(s) while S: flag = 0 @@ -87,7 +83,7 @@ def dfs(G, s): def bfs(G, s): - vis, Q = set([s]), deque([s]) + vis, Q = {s}, deque([s]) print(s) while Q: u = Q.popleft() @@ -169,8 +165,7 @@ def topo(G, ind=None, Q=[1]): def adjm(): n, a = raw_input(), [] - for i in xrange(n): - a.append(map(int, raw_input().split())) + a.extend(map(int, raw_input().split()) for _ in xrange(n)) return a, n @@ -190,7 +185,7 @@ def adjm(): def floy(A_and_n): (A, n) = A_and_n dist = list(A) - path = [[0] * n for i in xrange(n)] + path = [[0] * n for _ in xrange(n)] for k in xrange(n): for i in xrange(n): for j in xrange(n): @@ -243,9 +238,7 @@ def prim(G, s): def edglist(): n, m = map(int, raw_input().split(" ")) - l = [] - for i in xrange(m): - l.append(map(int, raw_input().split(' '))) + l = [map(int, raw_input().split(' ')) for _ in xrange(m)] return l, n @@ -263,7 +256,7 @@ def krusk(E_and_n): # Sort edges on the basis of distance (E, n) = E_and_n E.sort(reverse=True, key=lambda x: x[2]) - s = [set([i]) for i in range(1, n + 1)] + s = [{i} for i in range(1, n + 1)] while True: if len(s) == 1: break @@ -283,8 +276,4 @@ def krusk(E_and_n): # find the isolated node in the graph def find_isolated_nodes(graph): - isolated = [] - for node in graph: - if not graph[node]: - isolated.append(node) - return isolated + return [node for node in graph if not graph[node]] diff --git a/Graphs/bellman_ford.py b/Graphs/bellman_ford.py index 82db805..2466630 100644 --- a/Graphs/bellman_ford.py +++ b/Graphs/bellman_ford.py @@ -10,17 +10,17 @@ def printDist(dist, V): print() def BellmanFord(graph, V, E, src): - mdist=[float('inf') for i in range(V)] + mdist = [float('inf') for _ in range(V)] mdist[src] = 0.0 - - for i in range(V-1): + + for _ in range(V-1): for j in range(V): u = graph[j]["src"] v = graph[j]["dst"] w = graph[j]["weight"] if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: - mdist[v] = mdist[u] + w + mdist[v] = mdist[u] + w for j in range(V): u = graph[j]["src"] v = graph[j]["dst"] @@ -29,7 +29,7 @@ def BellmanFord(graph, V, E, src): if mdist[u] != float('inf') and mdist[u] + w < mdist[v]: print("Negative cycle found. Solution not possible.") return - + printDist(mdist, V) @@ -38,7 +38,7 @@ def BellmanFord(graph, V, E, src): V = int(input("Enter number of vertices: ")) E = int(input("Enter number of edges: ")) -graph = [dict() for j in range(E)] +graph = [dict() for _ in range(E)] for i in range(V): graph[i][i] = 0.0 @@ -49,6 +49,6 @@ def BellmanFord(graph, V, E, src): dst = int(input("Enter destination:")) weight = float(input("Enter weight:")) graph[i] = {"src": src,"dst": dst, "weight": weight} - + gsrc = int(input("\nEnter shortest path source:")) BellmanFord(graph, V, E, gsrc) diff --git a/Graphs/breadth_first_search.py b/Graphs/breadth_first_search.py index 3992e2d..0d20acb 100644 --- a/Graphs/breadth_first_search.py +++ b/Graphs/breadth_first_search.py @@ -28,13 +28,9 @@ def BFS(self, startVertex): # Take a list for stoting already visited vertexes visited = [False] * len(self.vertex) - # create a list to store all the vertexes for BFS - queue = [] - # mark the source node as visited and enqueue it visited[startVertex] = True - queue.append(startVertex) - + queue = [startVertex] while queue: startVertex = queue.pop(0) print(startVertex, end = ' ') diff --git a/Graphs/dijkstra_2.py b/Graphs/dijkstra_2.py index a6c340e..50cab84 100644 --- a/Graphs/dijkstra_2.py +++ b/Graphs/dijkstra_2.py @@ -19,19 +19,19 @@ def minDist(mdist, vset, V): return minInd def Dijkstra(graph, V, src): - mdist=[float('inf') for i in range(V)] - vset = [False for i in range(V)] + mdist = [float('inf') for _ in range(V)] + vset = [False for _ in range(V)] mdist[src] = 0.0 - - for i in range(V-1): + + for _ in range(V-1): u = minDist(mdist, vset, V) vset[u] = True - + for v in range(V): if (not vset[v]) and graph[u][v]!=float('inf') and mdist[u] + graph[u][v] < mdist[v]: mdist[v] = mdist[u] + graph[u][v] - + printDist(mdist, V) @@ -41,7 +41,7 @@ def Dijkstra(graph, V, src): V = int(input("Enter number of vertices: ")) E = int(input("Enter number of edges: ")) -graph = [[float('inf') for i in range(V)] for j in range(V)] +graph = [[float('inf') for _ in range(V)] for _ in range(V)] for i in range(V): graph[i][i] = 0.0 diff --git a/Graphs/dijkstra_algorithm.py b/Graphs/dijkstra_algorithm.py index 985c7f6..cc217d7 100644 --- a/Graphs/dijkstra_algorithm.py +++ b/Graphs/dijkstra_algorithm.py @@ -103,8 +103,7 @@ def add_edge(self, u, v, w): def show_graph(self): # u -> v(w) for u in self.adjList: - print(u, '->', ' -> '.join(str("{}({})".format(v, w)) - for v, w in self.adjList[u])) + print(u, '->', ' -> '.join(f"{v}({w})" for v, w in self.adjList[u])) def dijkstra(self, src): # Flush old junk values in par[] @@ -136,9 +135,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 @@ -158,9 +157,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='') diff --git a/Graphs/even_tree.py b/Graphs/even_tree.py index 9383ea9..21701c5 100644 --- a/Graphs/even_tree.py +++ b/Graphs/even_tree.py @@ -19,12 +19,8 @@ def dfs(start): """DFS traversal""" - # pylint: disable=redefined-outer-name - ret = 1 visited[start] = True - for v in tree.get(start): - if v not in visited: - ret += dfs(v) + ret = 1 + sum(dfs(v) for v in tree.get(start) if v not in visited) if ret % 2 == 0: cuts.append(start) return ret diff --git a/Graphs/floyd_warshall.py b/Graphs/floyd_warshall.py index fae8b19..849e90e 100644 --- a/Graphs/floyd_warshall.py +++ b/Graphs/floyd_warshall.py @@ -13,8 +13,8 @@ def printDist(dist, V): def FloydWarshall(graph, V): - dist=[[float('inf') for i in range(V)] for j in range(V)] - + dist = [[float('inf') for _ in range(V)] for _ in range(V)] + for i in range(V): for j in range(V): dist[i][j] = graph[i][j] @@ -33,7 +33,7 @@ def FloydWarshall(graph, V): V = int(input("Enter number of vertices: ")) E = int(input("Enter number of edges: ")) -graph = [[float('inf') for i in range(V)] for j in range(V)] +graph = [[float('inf') for _ in range(V)] for _ in range(V)] for i in range(V): graph[i][i] = 0.0 diff --git a/Graphs/graph_list.py b/Graphs/graph_list.py index d67bc96..034de4f 100644 --- a/Graphs/graph_list.py +++ b/Graphs/graph_list.py @@ -4,7 +4,7 @@ class Graph: def __init__(self, vertex): self.vertex = vertex - self.graph = [[0] for i in range(vertex)] + self.graph = [[0] for _ in range(vertex)] def add_edge(self, u, v): self.graph[u - 1].append(v - 1) diff --git a/Graphs/graph_matrix.py b/Graphs/graph_matrix.py index de25301..6a8c05f 100644 --- a/Graphs/graph_matrix.py +++ b/Graphs/graph_matrix.py @@ -5,7 +5,7 @@ class Graph: def __init__(self, vertex): self.vertex = vertex - self.graph = [[0] * vertex for i in range(vertex) ] + self.graph = [[0] * vertex for _ in range(vertex)] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 diff --git a/Graphs/kahns_algorithm_long.py b/Graphs/kahns_algorithm_long.py index 453b570..1a90fd2 100644 --- a/Graphs/kahns_algorithm_long.py +++ b/Graphs/kahns_algorithm_long.py @@ -1,17 +1,13 @@ # Finding longest distance in Directed Acyclic Graph using KahnsAlgorithm def longestDistance(l): indegree = [0] * len(l) - queue = [] longDist = [1] * len(l) for key, values in l.items(): for i in values: indegree[i] += 1 - for i in range(len(indegree)): - if indegree[i] == 0: - queue.append(i) - + queue = [i for i in range(len(indegree)) if indegree[i] == 0] while(queue): vertex = queue.pop(0) for x in l[vertex]: diff --git a/Graphs/kahns_algorithm_topo.py b/Graphs/kahns_algorithm_topo.py index 8c182c4..a5b9451 100644 --- a/Graphs/kahns_algorithm_topo.py +++ b/Graphs/kahns_algorithm_topo.py @@ -1,7 +1,6 @@ # Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS def topologicalSort(l): indegree = [0] * len(l) - queue = [] topo = [] cnt = 0 @@ -9,10 +8,7 @@ def topologicalSort(l): for i in values: indegree[i] += 1 - for i in range(len(indegree)): - if indegree[i] == 0: - queue.append(i) - + queue = [i for i in range(len(indegree)) if indegree[i] == 0] while(queue): vertex = queue.pop(0) cnt += 1 diff --git a/Graphs/minimum_spanning_tree_kruskal.py b/Graphs/minimum_spanning_tree_kruskal.py index 81d64f4..fadfdf1 100644 --- a/Graphs/minimum_spanning_tree_kruskal.py +++ b/Graphs/minimum_spanning_tree_kruskal.py @@ -9,7 +9,7 @@ edges = sorted(edges, key=lambda edge: edge[3]) -parent = [i for i in range(num_nodes)] +parent = list(range(num_nodes)) def find_parent(i): if(i != parent[i]): diff --git a/Graphs/minimum_spanning_tree_prims.py b/Graphs/minimum_spanning_tree_prims.py index 7b1ad0e..16f5568 100644 --- a/Graphs/minimum_spanning_tree_prims.py +++ b/Graphs/minimum_spanning_tree_prims.py @@ -13,35 +13,31 @@ def setPosition(vertex, pos): def topToBottom(heap, start, size, positions): if start > size // 2 - 1: return + if 2 * start + 2 >= size: + m = 2 * start + 1 else: - if 2 * start + 2 >= size: - m = 2 * start + 1 - else: - if heap[2 * start + 1] < heap[2 * start + 2]: - m = 2 * start + 1 - else: - m = 2 * start + 2 - if heap[m] < heap[start]: - temp, temp1 = heap[m], positions[m] - heap[m], positions[m] = heap[start], positions[start] - heap[start], positions[start] = temp, temp1 - - temp = getPosition(positions[m]) - setPosition(positions[m], getPosition(positions[start])) - setPosition(positions[start], temp) - - topToBottom(heap, m, size, positions) + m = ( + 2 * start + 1 + if heap[2 * start + 1] < heap[2 * start + 2] + else 2 * start + 2 + ) + if heap[m] < heap[start]: + temp, temp1 = heap[m], positions[m] + heap[m], positions[m] = heap[start], positions[start] + heap[start], positions[start] = temp, temp1 + + temp = getPosition(positions[m]) + setPosition(positions[m], getPosition(positions[start])) + setPosition(positions[start], temp) + + topToBottom(heap, m, size, positions) # Update function if value of any node in min-heap decreases def bottomToTop(val, index, heap, position): temp = position[index] - while(index != 0): - if index % 2 == 0: - parent = int( (index-2) / 2 ) - else: - parent = int( (index-1) / 2 ) - + while (index != 0): + parent = int( (index-2) / 2 ) if index % 2 == 0 else int( (index-1) / 2 ) if val < heap[parent]: heap[index] = heap[parent] position[index] = position[parent] @@ -104,7 +100,7 @@ def deleteMinimum(heap, positions): n = int(input("Enter number of vertices: ")) e = int(input("Enter number of edges: ")) adjlist = defaultdict(list) -for x in range(e): +for _ in range(e): l = [int(x) for x in input().split()] adjlist[l[0]].append([ l[1], l[2] ]) adjlist[l[1]].append([ l[0], l[2] ]) diff --git a/Graphs/multi_hueristic_astar.py b/Graphs/multi_hueristic_astar.py index 1acd098..1e7255f 100644 --- a/Graphs/multi_hueristic_astar.py +++ b/Graphs/multi_hueristic_astar.py @@ -14,10 +14,7 @@ def __init__(self): self.set = set() def minkey(self): - if not self.empty(): - return self.elements[0][0] - else: - return float('inf') + return self.elements[0][0] if not self.empty() else float('inf') def empty(self): return len(self.elements) == 0 @@ -72,8 +69,7 @@ def hueristic_1(P, goal): return abs(P[0] - goal[0]) + abs(P[1] - goal[1]) def key(start, i, goal, g_function): - ans = g_function[start] + W1 * hueristics[i](start, goal) - return ans + return g_function[start] + W1 * hueristics[i](start, goal) def do_something(back_pointer, goal, start): grid = np.chararray((n, n)) @@ -118,11 +114,7 @@ def do_something(back_pointer, goal, start): quit() def valid(p): - if p[0] < 0 or p[0] > n-1: - return False - if p[1] < 0 or p[1] > n-1: - return False - return True + return False if p[0] < 0 or p[0] > n-1 else p[1] >= 0 and p[1] <= n-1 def expand_state(s, j, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer): for itera in range(n_hueristic): @@ -158,29 +150,21 @@ def expand_state(s, j, visited, g_function, close_list_anchor, close_list_inad, # print def make_common_ground(): - some_list = [] - # block 1 - for x in range(1, 5): - for y in range(1, 6): - some_list.append((x, y)) - - # line - for x in range(15, 20): - some_list.append((x, 17)) - - # block 2 big - for x in range(10, 19): - for y in range(1, 15): - some_list.append((x, y)) - - # L block - for x in range(1, 4): - for y in range(12, 19): - some_list.append((x, y)) - for x in range(3, 13): - for y in range(16, 19): - some_list.append((x, y)) - return some_list + some_list = [] + # block 1 + for x in range(1, 5): + some_list.extend((x, y) for y in range(1, 6)) + # line + some_list.extend((x, 17) for x in range(15, 20)) + # block 2 big + for x in range(10, 19): + some_list.extend((x, y) for y in range(1, 15)) + # L block + for x in range(1, 4): + some_list.extend((x, y) for y in range(12, 19)) + for x in range(3, 13): + some_list.extend((x, y) for y in range(16, 19)) + return some_list hueristics = {0: consistent_hueristic, 1: hueristic_1, 2: hueristic_2} @@ -204,63 +188,61 @@ def make_common_ground(): t = 1 def multi_a_star(start, goal, n_hueristic): - g_function = {start: 0, goal: float('inf')} - back_pointer = {start:-1, goal:-1} - open_list = [] - visited = set() - - for i in range(n_hueristic): - open_list.append(PriorityQueue()) - open_list[i].put(start, key(start, i, goal, g_function)) - - close_list_anchor = [] - close_list_inad = [] - while open_list[0].minkey() < float('inf'): - for i in range(1, n_hueristic): - # print("i", i) - # print(open_list[0].minkey(), open_list[i].minkey()) - if open_list[i].minkey() <= W2 * open_list[0].minkey(): - global t - t += 1 - # print("less prio") - if g_function[goal] <= open_list[i].minkey(): - if g_function[goal] < float('inf'): - do_something(back_pointer, goal, start) - else: - _, get_s = open_list[i].top_show() - visited.add(get_s) - expand_state(get_s, i, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) - close_list_inad.append(get_s) - else: - # print("more prio") - if g_function[goal] <= open_list[0].minkey(): - if g_function[goal] < float('inf'): - do_something(back_pointer, goal, start) - else: - # print("hoolla") - get_s = open_list[0].top_show() - visited.add(get_s) - expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) - close_list_anchor.append(get_s) - print("No path found to goal") - print() - for i in range(n-1,-1, -1): - for j in range(n): - if (j, i) in blocks: - print('#', end=' ') - elif (j, i) in back_pointer: - if (j, i) == (n-1, n-1): - print('*', end=' ') - else: - print('-', end=' ') - else: - print('*', end=' ') - if (j, i) == (n-1, n-1): - print('<-- End position', end=' ') - print() - print("^") - print("Start position") - print() - print("# is an obstacle") - print("- is the path taken by algorithm") + g_function = {start: 0, goal: float('inf')} + back_pointer = {start:-1, goal:-1} + open_list = [] + visited = set() + + for i in range(n_hueristic): + open_list.append(PriorityQueue()) + open_list[i].put(start, key(start, i, goal, g_function)) + + close_list_anchor = [] + close_list_inad = [] + while open_list[0].minkey() < float('inf'): + for i in range(1, n_hueristic): + # print("i", i) + # print(open_list[0].minkey(), open_list[i].minkey()) + if open_list[i].minkey() <= W2 * open_list[0].minkey(): + global t + t += 1 + # print("less prio") + if g_function[goal] <= open_list[i].minkey(): + if g_function[goal] < float('inf'): + do_something(back_pointer, goal, start) + else: + _, get_s = open_list[i].top_show() + visited.add(get_s) + expand_state(get_s, i, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) + close_list_inad.append(get_s) + elif g_function[goal] <= open_list[0].minkey(): + if g_function[goal] < float('inf'): + do_something(back_pointer, goal, start) + else: + # print("hoolla") + get_s = open_list[0].top_show() + visited.add(get_s) + expand_state(get_s, 0, visited, g_function, close_list_anchor, close_list_inad, open_list, back_pointer) + close_list_anchor.append(get_s) + print("No path found to goal") + print() + for i in range(n-1,-1, -1): + for j in range(n): + if (j, i) in blocks: + print('#', end=' ') + elif (j, i) in back_pointer: + if (j, i) == (n-1, n-1): + print('*', end=' ') + else: + print('-', end=' ') + else: + print('*', end=' ') + if (j, i) == (n-1, n-1): + print('<-- End position', end=' ') + print() + print("^") + print("Start position") + print() + print("# is an obstacle") + print("- is the path taken by algorithm") multi_a_star(start, goal, n_hueristic) diff --git a/Graphs/scc_kosaraju.py b/Graphs/scc_kosaraju.py index 1f13eba..4259aa5 100644 --- a/Graphs/scc_kosaraju.py +++ b/Graphs/scc_kosaraju.py @@ -2,10 +2,10 @@ # n - no of nodes, m - no of edges n, m = list(map(int,input().split())) -g = [[] for i in range(n)] #graph -r = [[] for i in range(n)] #reversed graph +g = [[] for _ in range(n)] +r = [[] for _ in range(n)] # input graph data (edges) -for i in range(m): +for _ in range(m): u, v = list(map(int,input().split())) g[u].append(v) r[v].append(u) diff --git a/Graphs/tarjans_scc.py b/Graphs/tarjans_scc.py index 89754e5..f91d96f 100644 --- a/Graphs/tarjans_scc.py +++ b/Graphs/tarjans_scc.py @@ -72,7 +72,7 @@ def create_graph(n, edges): n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] - edges = [(u, v) for u, v in zip(source, target)] + edges = list(zip(source, target)) g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g) diff --git a/Maths/abs.py b/Maths/abs.py index 6d05964..9e24340 100644 --- a/Maths/abs.py +++ b/Maths/abs.py @@ -6,10 +6,7 @@ def absVal(num): >>absVal(0) 0 """ - if num < 0: - return -num - else: - return num + return -num if num < 0 else num def main(): print(absVal(-34)) # = 34 diff --git a/Maths/extended_euclidean_algorithm.py b/Maths/extended_euclidean_algorithm.py index f5a3cc8..c599253 100644 --- a/Maths/extended_euclidean_algorithm.py +++ b/Maths/extended_euclidean_algorithm.py @@ -9,8 +9,12 @@ # Finds 2 numbers a and b such that it satisfies # the equation am + bn = gcd(m, n) (a.k.a Bezout's Identity) def extended_euclidean_algorithm(m, n): - a = 0; aprime = 1; b = 1; bprime = 0 - q = 0; r = 0 + a = 0 + aprime = 1 + b = 1 + bprime = 0 + q = 0 + r = 0 if m > n: c = m; d = n else: @@ -33,11 +37,7 @@ def extended_euclidean_algorithm(m, n): b = t - q*b pair = None - if m > n: - pair = (a,b) - else: - pair = (b,a) - return pair + return (a, b) if m > n else (b, a) def main(): if len(sys.argv) < 3: diff --git a/Maths/find_lcm.py b/Maths/find_lcm.py index 1262426..61a5093 100644 --- a/Maths/find_lcm.py +++ b/Maths/find_lcm.py @@ -1,5 +1,5 @@ def find_lcm(num_1, num_2): - max = num_1 if num_1 > num_2 else num_2 + max = max(num_1, num_2) lcm = max while (True): if ((lcm % num_1 == 0) and (lcm % num_2 == 0)): diff --git a/analysis/compression_analysis/psnr.py b/analysis/compression_analysis/psnr.py index 0f21aac..9a97dc0 100644 --- a/analysis/compression_analysis/psnr.py +++ b/analysis/compression_analysis/psnr.py @@ -11,11 +11,7 @@ def psnr(original, contrast): mse = np.mean((original - contrast) ** 2) - if mse == 0: - return 100 - PIXEL_MAX = 255.0 - PSNR = 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) - return PSNR + return 100 if mse == 0 else 20 * math.log10(255.0 / math.sqrt(mse)) def main(): diff --git a/binary_tree/basic_binary_tree.py b/binary_tree/basic_binary_tree.py index 5738e4e..8bced7c 100644 --- a/binary_tree/basic_binary_tree.py +++ b/binary_tree/basic_binary_tree.py @@ -8,13 +8,9 @@ def __init__(self, data): def depth_of_tree(tree): #This is the recursive function to find the depth of binary tree. if tree is None: return 0 - else: - depth_l_tree = depth_of_tree(tree.left) - depth_r_tree = depth_of_tree(tree.right) - if depth_l_tree > depth_r_tree: - return 1 + depth_l_tree - else: - return 1 + depth_r_tree + depth_l_tree = depth_of_tree(tree.left) + depth_r_tree = depth_of_tree(tree.right) + return 1 + depth_l_tree if depth_l_tree > depth_r_tree else 1 + depth_r_tree def is_full_binary_tree(tree): # This functions returns that is it full binary tree or not? diff --git a/boolean_algebra/quine_mc_cluskey.py b/boolean_algebra/quine_mc_cluskey.py index db4d153..38ed3a0 100644 --- a/boolean_algebra/quine_mc_cluskey.py +++ b/boolean_algebra/quine_mc_cluskey.py @@ -1,14 +1,12 @@ def compare_string(string1, string2): - l1 = list(string1); l2 = list(string2) + l1 = list(string1) + l2 = list(string2) count = 0 for i in range(len(l1)): if l1[i] != l2[i]: count += 1 l1[i] = '_' - if count > 1: - return -1 - else: - return("".join(l1)) + return -1 if count > 1 else ("".join(l1)) def check(binary): pi = [] @@ -22,10 +20,8 @@ def check(binary): check1[i] = '*' check1[j] = '*' temp.append(k) - for i in range(len(binary)): - if check1[i] == '$': - pi.append(binary[i]) - if len(temp) == 0: + pi.extend(binary[i] for i in range(len(binary)) if check1[i] == '$') + if not temp: return pi binary = list(set(temp)) @@ -33,7 +29,7 @@ def decimal_to_binary(no_of_variable, minterms): temp = [] s = '' for m in minterms: - for i in range(no_of_variable): + for _ in range(no_of_variable): s = str(m%2) + s m //= 2 temp.append(s) @@ -41,15 +37,10 @@ def decimal_to_binary(no_of_variable, minterms): return temp def is_for_table(string1, string2, count): - l1 = list(string1);l2=list(string2) - count_n = 0 - for i in range(len(l1)): - if l1[i] != l2[i]: - count_n += 1 - if count_n == count: - return True - else: - return False + l1 = list(string1) + l2=list(string2) + count_n = sum(1 for i in range(len(l1)) if l1[i] != l2[i]) + return count_n == count def selection(chart, prime_implicants): temp = [] @@ -89,13 +80,13 @@ def selection(chart, prime_implicants): chart[j][i] = 0 def prime_implicant_chart(prime_implicants, binary): - chart = [[0 for x in range(len(binary))] for x in range(len(prime_implicants))] + chart = [[0 for _ in range(len(binary))] for _ in range(len(prime_implicants))] for i in range(len(prime_implicants)): count = prime_implicants[i].count('_') for j in range(len(binary)): if(is_for_table(prime_implicants[i], binary[j], count)): chart[i][j] = 1 - + return chart def main(): diff --git a/ciphers/affine_cipher.py b/ciphers/affine_cipher.py index af5f4e0..68cc354 100644 --- a/ciphers/affine_cipher.py +++ b/ciphers/affine_cipher.py @@ -27,9 +27,13 @@ def checkKeys(keyA, keyB, mode): if keyB == 0 and mode == 'encrypt': sys.exit('The affine cipher becomes weak when key A is set to 1. Choose different key') if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1: - sys.exit('Key A must be greater than 0 and key B must be between 0 and %s.' % (len(SYMBOLS) - 1)) + sys.exit( + f'Key A must be greater than 0 and key B must be between 0 and {len(SYMBOLS) - 1}.' + ) if cryptoMath.gcd(keyA, len(SYMBOLS)) != 1: - sys.exit('Key A %s and the symbol set size %s are not relatively prime. Choose a different key.' % (keyA, len(SYMBOLS))) + sys.exit( + f'Key A {keyA} and the symbol set size {len(SYMBOLS)} are not relatively prime. Choose a different key.' + ) def encryptMessage(key, message): ''' diff --git a/ciphers/base64_cipher.py b/ciphers/base64_cipher.py index fa3451c..04d6cd7 100644 --- a/ciphers/base64_cipher.py +++ b/ciphers/base64_cipher.py @@ -1,59 +1,51 @@ def encodeBase64(text): base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" - + r = "" #the result c = 3 - len(text) % 3 #the length of padding p = "=" * c #the padding s = text + "\0" * c #the text to encode - - i = 0 - while i < len(s): + + for i in range(0, len(s), 3): if i > 0 and ((i / 3 * 4) % 76) == 0: r = r + "\r\n" - + n = (ord(s[i]) << 16) + (ord(s[i+1]) << 8 ) + ord(s[i+2]) - + n1 = (n >> 18) & 63 n2 = (n >> 12) & 63 n3 = (n >> 6) & 63 n4 = n & 63 - - r += base64chars[n1] + base64chars[n2] + base64chars[n3] + base64chars[n4] - i += 3 - return r[0: len(r)-len(p)] + p + r += base64chars[n1] + base64chars[n2] + base64chars[n3] + base64chars[n4] + return r[:len(r)-len(p)] + p def decodeBase64(text): base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" s = "" - + for i in text: if i in base64chars: s += i c = "" - else: - if i == '=': - c += '=' - + elif i == '=': + c += '=' + p = "" if c == "=": p = 'A' - else: - if c == "==": - p = "AA" - + elif c == "==": + p = "AA" + r = "" s = s + p - - i = 0 - while i < len(s): + + for i in range(0, len(s), 4): n = (base64chars.index(s[i]) << 18) + (base64chars.index(s[i+1]) << 12) + (base64chars.index(s[i+2]) << 6) +base64chars.index(s[i+3]) - + r += chr((n >> 16) & 255) + chr((n >> 8) & 255) + chr(n & 255) - - i += 4 - - return r[0: len(r) - len(p)] + + return r[:len(r) - len(p)] def main(): print(encodeBase64("WELCOME to base64 encoding")) diff --git a/ciphers/brute_force_caesar_cipher.py b/ciphers/brute_force_caesar_cipher.py index 3b07164..adba467 100644 --- a/ciphers/brute_force_caesar_cipher.py +++ b/ciphers/brute_force_caesar_cipher.py @@ -35,13 +35,13 @@ def decrypt(message): for symbol in message: if symbol in LETTERS: num = LETTERS.find(symbol) - num = num - key + num -= key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + symbol - print("Decryption using Key #%s: %s" % (key, translated)) + print(f"Decryption using Key #{key}: {translated}") def main(): message = input("Encrypted message: ") diff --git a/ciphers/caesar_cipher.py b/ciphers/caesar_cipher.py index 39c069c..d888e64 100644 --- a/ciphers/caesar_cipher.py +++ b/ciphers/caesar_cipher.py @@ -19,17 +19,15 @@ def decrypt(strng, key): return decrypted def brute_force(strng): - key = 1 decrypted = '' - while key <= 94: + for key in range(1, 95): for x in strng: indx = (ord(x) - key) % 256 if indx < 32: indx = indx + 95 decrypted = decrypted + chr(indx) - print("Key: {}\t| Message: {}".format(key, decrypted)) + print(f"Key: {key}\t| Message: {decrypted}") decrypted = '' - key += 1 return None diff --git a/ciphers/elgamal_key_generator.py b/ciphers/elgamal_key_generator.py index 6a8751f..d7a4ec2 100644 --- a/ciphers/elgamal_key_generator.py +++ b/ciphers/elgamal_key_generator.py @@ -41,7 +41,9 @@ def generateKey(keySize): def makeKeyFiles(name, keySize): - if os.path.exists('%s_pubkey.txt' % name) or os.path.exists('%s_privkey.txt' % name): + if os.path.exists(f'{name}_pubkey.txt') or os.path.exists( + f'{name}_privkey.txt' + ): print('\nWARNING:') print('"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' 'Use a different name or delete these files and re-run this program.' % @@ -50,11 +52,11 @@ def makeKeyFiles(name, keySize): publicKey, privateKey = generateKey(keySize) print('\nWriting public key to file %s_pubkey.txt...' % name) - with open('%s_pubkey.txt' % name, 'w') as fo: + with open(f'{name}_pubkey.txt', 'w') as fo: fo.write('%d,%d,%d,%d' % (publicKey[0], publicKey[1], publicKey[2], publicKey[3])) - print('Writing private key to file %s_privkey.txt...' % name) - with open('%s_privkey.txt' % name, 'w') as fo: + print(f'Writing private key to file {name}_privkey.txt...') + with open(f'{name}_privkey.txt', 'w') as fo: fo.write('%d,%d' % (privateKey[0], privateKey[1])) diff --git a/ciphers/hill_cipher.py b/ciphers/hill_cipher.py index 89b88be..d94e417 100644 --- a/ciphers/hill_cipher.py +++ b/ciphers/hill_cipher.py @@ -42,9 +42,7 @@ def gcd(a, b): - if a == 0: - return b - return gcd(b%a, a) + return b if a == 0 else gcd(b%a, a) class HillCipher: @@ -105,17 +103,19 @@ def encrypt(self, text): def makeDecryptKey(self): det = round(numpy.linalg.det(self.encrypt_key)) - + if det < 0: det = det % len(self.key_string) - det_inv = None - for i in range(len(self.key_string)): - if (det * i) % len(self.key_string) == 1: - det_inv = i - break - + det_inv = next( + ( + i + for i in range(len(self.key_string)) + if (det * i) % len(self.key_string) == 1 + ), + None, + ) inv_key = det_inv * numpy.linalg.det(self.encrypt_key) *\ - numpy.linalg.inv(self.encrypt_key) + numpy.linalg.inv(self.encrypt_key) return self.toInt(self.modulus(inv_key)) @@ -140,7 +140,7 @@ def main(): hill_matrix = [] print("Enter each row of the encryption key with space separated integers") - for i in range(N): + for _ in range(N): row = list(map(int, input().split())) hill_matrix.append(row) diff --git a/ciphers/onepad_cipher.py b/ciphers/onepad_cipher.py index 6afbd45..ed8150a 100644 --- a/ciphers/onepad_cipher.py +++ b/ciphers/onepad_cipher.py @@ -18,12 +18,8 @@ def encrypt(self, text): def decrypt(self, cipher, key): '''Function to decrypt text using psedo-random numbers.''' - plain = [] - for i in range(len(key)): - p = int((cipher[i]-(key[i])**2)/key[i]) - plain.append(chr(p)) - plain = ''.join([i for i in plain]) - return plain + plain = [chr(int((cipher[i]-(key[i])**2)/key[i])) for i in range(len(key))] + return ''.join(list(plain)) if __name__ == '__main__': diff --git a/ciphers/playfair_cipher.py b/ciphers/playfair_cipher.py index 20449b1..b0d4328 100644 --- a/ciphers/playfair_cipher.py +++ b/ciphers/playfair_cipher.py @@ -4,10 +4,10 @@ def chunker(seq, size): it = iter(seq) while True: - chunk = tuple(itertools.islice(it, size)) - if not chunk: - return - yield chunk + if chunk := tuple(itertools.islice(it, size)): + yield chunk + else: + return diff --git a/ciphers/rabin_miller.py b/ciphers/rabin_miller.py index f71fb03..f36dfe2 100644 --- a/ciphers/rabin_miller.py +++ b/ciphers/rabin_miller.py @@ -11,7 +11,7 @@ def rabinMiller(num): s = s // 2 t += 1 - for trials in range(5): + for _ in range(5): a = random.randrange(2, num - 1) v = pow(a, s, num) if v != 1: @@ -19,9 +19,8 @@ def rabinMiller(num): while v != (num - 1): if i == t - 1: return False - else: - i = i + 1 - v = (v ** 2) % num + i = i + 1 + v = (v ** 2) % num return True def isPrime(num): diff --git a/ciphers/rsa_cipher.py b/ciphers/rsa_cipher.py index d81f1ff..d58263a 100644 --- a/ciphers/rsa_cipher.py +++ b/ciphers/rsa_cipher.py @@ -13,28 +13,25 @@ def main(): elif response.lower().startswith('d'): mode = 'decrypt' - if mode == 'encrypt': - if not os.path.exists('rsa_pubkey.txt'): - rkg.makeKeyFiles('rsa', 1024) - - message = input('\nEnter message: ') - pubKeyFilename = 'rsa_pubkey.txt' - print('Encrypting and writing to %s...' % (filename)) - encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message) - - print('\nEncrypted text:') - print(encryptedText) - - elif mode == 'decrypt': - privKeyFilename = 'rsa_privkey.txt' - print('Reading from %s and decrypting...' % (filename)) - decryptedText = readFromFileAndDecrypt(filename, privKeyFilename) + if mode == 'decrypt': + print(f'Reading from {filename} and decrypting...') + decryptedText = readFromFileAndDecrypt(filename, 'rsa_privkey.txt') print('writing decryption to rsa_decryption.txt...') with open('rsa_decryption.txt', 'w') as dec: dec.write(decryptedText) print('\nDecryption:') print(decryptedText) + elif mode == 'encrypt': + if not os.path.exists('rsa_pubkey.txt'): + rkg.makeKeyFiles('rsa', 1024) + + message = input('\nEnter message: ') + print(f'Encrypting and writing to {filename}...') + encryptedText = encryptAndWriteToFile(filename, 'rsa_pubkey.txt', message) + + print('\nEncrypted text:') + print(encryptedText) def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE): @@ -42,9 +39,12 @@ def getBlocksFromText(message, blockSize=DEFAULT_BLOCK_SIZE): blockInts = [] for blockStart in range(0, len(messageBytes), blockSize): - blockInt = 0 - for i in range(blockStart, min(blockStart + blockSize, len(messageBytes))): - blockInt += messageBytes[i] * (BYTE_SIZE ** (i % blockSize)) + blockInt = sum( + messageBytes[i] * (BYTE_SIZE ** (i % blockSize)) + for i in range( + blockStart, min(blockStart + blockSize, len(messageBytes)) + ) + ) blockInts.append(blockInt) return blockInts @@ -63,19 +63,14 @@ def getTextFromBlocks(blockInts, messageLength, blockSize=DEFAULT_BLOCK_SIZE): def encryptMessage(message, key, blockSize=DEFAULT_BLOCK_SIZE): - encryptedBlocks = [] n, e = key - for block in getBlocksFromText(message, blockSize): - encryptedBlocks.append(pow(block, e, n)) - return encryptedBlocks + return [pow(block, e, n) for block in getBlocksFromText(message, blockSize)] def decryptMessage(encryptedBlocks, messageLength, key, blockSize=DEFAULT_BLOCK_SIZE): - decryptedBlocks = [] n, d = key - for block in encryptedBlocks: - decryptedBlocks.append(pow(block, d, n)) + decryptedBlocks = [pow(block, d, n) for block in encryptedBlocks] return getTextFromBlocks(decryptedBlocks, messageLength, blockSize) @@ -89,14 +84,16 @@ def readKeyFile(keyFilename): def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=DEFAULT_BLOCK_SIZE): keySize, n, e = readKeyFile(keyFilename) if keySize < blockSize * 8: - sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Either decrease the block size or use different keys.' % (blockSize * 8, keySize)) + sys.exit( + f'ERROR: Block size is {blockSize * 8} bits and key size is {keySize} bits. The RSA cipher requires the block size to be equal to or greater than the key size. Either decrease the block size or use different keys.' + ) encryptedBlocks = encryptMessage(message, (n, e), blockSize) for i in range(len(encryptedBlocks)): encryptedBlocks[i] = str(encryptedBlocks[i]) encryptedContent = ','.join(encryptedBlocks) - encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent) + encryptedContent = f'{len(message)}_{blockSize}_{encryptedContent}' with open(messageFilename, 'w') as fo: fo.write(encryptedContent) return encryptedContent @@ -111,12 +108,11 @@ def readFromFileAndDecrypt(messageFilename, keyFilename): blockSize = int(blockSize) if keySize < blockSize * 8: - sys.exit('ERROR: Block size is %s bits and key size is %s bits. The RSA cipher requires the block size to be equal to or greater than the key size. Did you specify the correct key file and encrypted file?' % (blockSize * 8, keySize)) - - encryptedBlocks = [] - for block in encryptedMessage.split(','): - encryptedBlocks.append(int(block)) + sys.exit( + f'ERROR: Block size is {blockSize * 8} bits and key size is {keySize} bits. The RSA cipher requires the block size to be equal to or greater than the key size. Did you specify the correct key file and encrypted file?' + ) + encryptedBlocks = [int(block) for block in encryptedMessage.split(',')] return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize) if __name__ == '__main__': diff --git a/ciphers/rsa_key_generator.py b/ciphers/rsa_key_generator.py index 541e90d..efd407c 100644 --- a/ciphers/rsa_key_generator.py +++ b/ciphers/rsa_key_generator.py @@ -28,19 +28,21 @@ def generateKey(keySize): return (publicKey, privateKey) def makeKeyFiles(name, keySize): - if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)): + if os.path.exists(f'{name}_pubkey.txt') or os.path.exists( + f'{name}_privkey.txt' + ): print('\nWARNING:') print('"%s_pubkey.txt" or "%s_privkey.txt" already exists. \nUse a different name or delete these files and re-run this program.' % (name, name)) sys.exit() publicKey, privateKey = generateKey(keySize) print('\nWriting public key to file %s_pubkey.txt...' % name) - with open('%s_pubkey.txt' % name, 'w') as fo: - fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1])) + with open(f'{name}_pubkey.txt', 'w') as fo: + fo.write(f'{keySize},{publicKey[0]},{publicKey[1]}') - print('Writing private key to file %s_privkey.txt...' % name) - with open('%s_privkey.txt' % name, 'w') as fo: - fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1])) + print(f'Writing private key to file {name}_privkey.txt...') + with open(f'{name}_privkey.txt', 'w') as fo: + fo.write(f'{keySize},{privateKey[0]},{privateKey[1]}') if __name__ == '__main__': main() diff --git a/ciphers/simple_substitution_cipher.py b/ciphers/simple_substitution_cipher.py index 1bdd7dc..31f8561 100644 --- a/ciphers/simple_substitution_cipher.py +++ b/ciphers/simple_substitution_cipher.py @@ -20,9 +20,8 @@ def main(): print('\n%sion: \n%s' % (mode.title(), translated)) def checkValidKey(key): - keyList = list(key) lettersList = list(LETTERS) - keyList.sort() + keyList = sorted(key) lettersList.sort() if keyList != lettersList: diff --git a/ciphers/transposition_cipher.py b/ciphers/transposition_cipher.py index dbb3583..e84b79f 100644 --- a/ciphers/transposition_cipher.py +++ b/ciphers/transposition_cipher.py @@ -3,7 +3,7 @@ def main(): message = input('Enter message: ') - key = int(input('Enter key [2-%s]: ' % (len(message) - 1))) + key = int(input(f'Enter key [2-{len(message) - 1}]: ')) mode = input('Encryption/Decryption [e/d]: ') if mode.lower().startswith('e'): @@ -12,7 +12,7 @@ def main(): text = decryptMessage(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. - print('Output:\n%s' %(text + '|')) + print('Output:\n%s' % f'{text}|') def encryptMessage(key, message): """ diff --git a/ciphers/transposition_cipher_encrypt_decrypt_file.py b/ciphers/transposition_cipher_encrypt_decrypt_file.py index a186cf8..e6b51a5 100644 --- a/ciphers/transposition_cipher_encrypt_decrypt_file.py +++ b/ciphers/transposition_cipher_encrypt_decrypt_file.py @@ -9,14 +9,14 @@ def main(): mode = input('Encrypt/Decrypt [e/d]: ') if not os.path.exists(inputFile): - print('File %s does not exist. Quitting...' % inputFile) + print(f'File {inputFile} does not exist. Quitting...') sys.exit() if os.path.exists(outputFile): - print('Overwrite %s? [y/n]' % outputFile) + print(f'Overwrite {outputFile}? [y/n]') response = input('> ') if not response.lower().startswith('y'): sys.exit() - + startTime = time.time() if mode.lower().startswith('e'): with open(inputFile) as f: @@ -29,7 +29,7 @@ def main(): with open(outputFile, 'w') as outputObj: outputObj.write(translated) - + totalTime = round(time.time() - startTime, 2) print(('Done (', totalTime, 'seconds )')) diff --git a/ciphers/xor_cipher.py b/ciphers/xor_cipher.py index 727fac3..d0a8480 100644 --- a/ciphers/xor_cipher.py +++ b/ciphers/xor_cipher.py @@ -44,13 +44,7 @@ def encrypt(self, content, key): while (key > 255): key -= 255 - # This will be returned - ans = [] - - for ch in content: - ans.append(chr(ord(ch) ^ key)) - - return ans + return [chr(ord(ch) ^ key) for ch in content] def decrypt(self,content,key): """ @@ -69,13 +63,7 @@ def decrypt(self,content,key): while (key > 255): key -= 255 - # This will be returned - ans = [] - - for ch in content: - ans.append(chr(ord(ch) ^ key)) - - return ans + return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self,content, key = 0): @@ -95,13 +83,7 @@ def encrypt_string(self,content, key = 0): while (key > 255): key -= 255 - # This will be returned - ans = "" - - for ch in content: - ans += chr(ord(ch) ^ key) - - return ans + return "".join(chr(ord(ch) ^ key) for ch in content) def decrypt_string(self,content,key = 0): """ @@ -120,13 +102,7 @@ def decrypt_string(self,content,key = 0): while (key > 255): key -= 255 - # This will be returned - ans = "" - - for ch in content: - ans += chr(ord(ch) ^ key) - - return ans + return "".join(chr(ord(ch) ^ key) for ch in content) def encrypt_file(self, file, key = 0): diff --git a/data_structures/avl.py b/data_structures/avl.py index d01e8f8..05c3b33 100644 --- a/data_structures/avl.py +++ b/data_structures/avl.py @@ -69,10 +69,7 @@ def insert(self, value): dad_node = curr_node - if node.label < curr_node.label: - curr_node = curr_node.left - else: - curr_node = curr_node.right + curr_node = curr_node.left if node.label < curr_node.label else curr_node.right else: node.height = dad_node.height dad_node.height += 1 @@ -107,10 +104,8 @@ def rebalance(self, node): if (left_child.left is not None) else 0) if (h_left > h_right): self.rotate_left(n) - break else: self.double_rotate_right(n) - break else: right_child = n.right if right_child is not None: @@ -120,10 +115,9 @@ def rebalance(self, node): if (right_child.left is not None) else 0) if (h_left > h_right): self.double_rotate_left(n) - break else: self.rotate_right(n) - break + break n = n.parent def rotate_left(self, node): @@ -150,9 +144,7 @@ def double_rotate_right(self, node): self.rotate_right(node) def empty(self): - if self.root is None: - return True - return False + return self.root is None def preShow(self, curr_node): if curr_node is not None: diff --git a/data_structures/binary tree/AVLtree.py b/data_structures/binary tree/AVLtree.py index ff44963..c010cbe 100644 --- a/data_structures/binary tree/AVLtree.py +++ b/data_structures/binary tree/AVLtree.py @@ -53,14 +53,10 @@ def setheight(self,height): return def getheight(node): - if node is None: - return 0 - return node.getheight() + return 0 if node is None else node.getheight() def my_max(a,b): - if a > b: - return a - return b + return max(a, b) @@ -193,11 +189,11 @@ def getheight(self): # print("yyy") return getheight(self.root) def insert(self,data): - print("insert:"+str(data)) + print(f"insert:{str(data)}") self.root = insert_node(self.root,data) def del_node(self,data): - print("delete:"+str(data)) + print(f"delete:{str(data)}") if self.root is None: print("Tree is empty!") return diff --git a/data_structures/binary tree/binary_search_tree.py b/data_structures/binary tree/binary_search_tree.py index cef5b55..b8ca876 100644 --- a/data_structures/binary tree/binary_search_tree.py +++ b/data_structures/binary tree/binary_search_tree.py @@ -69,29 +69,30 @@ def insert(self, label): new_node.setParent(parent_node) def delete(self, label): - if (not self.empty()): - #Look for the node with that label - node = self.getNode(label) - #If the node exists - if(node is not None): - #If it has no children - if(node.getLeft() is None and node.getRight() is None): - self.__reassignNodes(node, None) - node = None - #Has only right children - elif(node.getLeft() is None and node.getRight() is not None): - self.__reassignNodes(node, node.getRight()) - #Has only left children - elif(node.getLeft() is not None and node.getRight() is None): - self.__reassignNodes(node, node.getLeft()) - #Has two children - else: - #Gets the max value of the left branch - tmpNode = self.getMax(node.getLeft()) - #Deletes the tmpNode - self.delete(tmpNode.getLabel()) - #Assigns the value to the node to delete and keesp tree structure - node.setLabel(tmpNode.getLabel()) + if self.empty(): + return + #Look for the node with that label + node = self.getNode(label) + #If the node exists + if(node is not None): + #If it has no children + if(node.getLeft() is None and node.getRight() is None): + self.__reassignNodes(node, None) + node = None + #Has only right children + elif(node.getLeft() is None and node.getRight() is not None): + self.__reassignNodes(node, node.getRight()) + #Has only left children + elif(node.getLeft() is not None and node.getRight() is None): + self.__reassignNodes(node, node.getLeft()) + #Has two children + else: + #Gets the max value of the left branch + tmpNode = self.getMax(node.getLeft()) + #Deletes the tmpNode + self.delete(tmpNode.getLabel()) + #Assigns the value to the node to delete and keesp tree structure + node.setLabel(tmpNode.getLabel()) def getNode(self, label): curr_node = None @@ -112,22 +113,14 @@ def getNode(self, label): return curr_node def getMax(self, root = None): - if(root is not None): - curr_node = root - else: - #We go deep on the right branch - curr_node = self.getRoot() + curr_node = root if (root is not None) else self.getRoot() if(not self.empty()): while(curr_node.getRight() is not None): curr_node = curr_node.getRight() return curr_node def getMin(self, root = None): - if(root is not None): - curr_node = root - else: - #We go deep on the left branch - curr_node = self.getRoot() + curr_node = root if (root is not None) else self.getRoot() if(not self.empty()): curr_node = self.getRoot() while(curr_node.getLeft() is not None): @@ -135,15 +128,13 @@ def getMin(self, root = None): return curr_node def empty(self): - if self.root is None: - return True - return False + return self.root is None def __InOrderTraversal(self, curr_node): nodeList = [] if curr_node is not None: nodeList.insert(0, curr_node) - nodeList = nodeList + self.__InOrderTraversal(curr_node.getLeft()) + nodeList += self.__InOrderTraversal(curr_node.getLeft()) nodeList = nodeList + self.__InOrderTraversal(curr_node.getRight()) return nodeList @@ -151,9 +142,7 @@ def getRoot(self): return self.root def __isRightChildren(self, node): - if(node == node.getParent().getRight()): - return True - return False + return node == node.getParent().getRight() def __reassignNodes(self, node, newChildren): if(newChildren is not None): @@ -183,13 +172,13 @@ def __str__(self): list = self.__InOrderTraversal(self.root) str = "" for x in list: - str = str + " " + x.getLabel().__str__() + str = f"{str} {x.getLabel().__str__()}" return str def InPreOrder(curr_node): nodeList = [] if curr_node is not None: - nodeList = nodeList + InPreOrder(curr_node.getLeft()) + nodeList += InPreOrder(curr_node.getLeft()) nodeList.insert(0, curr_node.getLabel()) nodeList = nodeList + InPreOrder(curr_node.getRight()) return nodeList diff --git a/data_structures/binary tree/fenwick_tree.py b/data_structures/binary tree/fenwick_tree.py index f429161..36df60b 100644 --- a/data_structures/binary tree/fenwick_tree.py +++ b/data_structures/binary tree/fenwick_tree.py @@ -3,7 +3,7 @@ class FenwickTree: def __init__(self, SIZE): # create fenwick tree with size SIZE self.Size = SIZE - self.ft = [0 for i in range (0,SIZE)] + self.ft = [0 for _ in range (0,SIZE)] def update(self, i, val): # update data (adding) in index i in O(lg N) while (i < self.Size): diff --git a/data_structures/binary tree/lazy_segment_tree.py b/data_structures/binary tree/lazy_segment_tree.py index 9b14b24..82ab902 100644 --- a/data_structures/binary tree/lazy_segment_tree.py +++ b/data_structures/binary tree/lazy_segment_tree.py @@ -5,9 +5,9 @@ class SegmentTree: def __init__(self, N): self.N = N - self.st = [0 for i in range(0,4*N)] # approximate the overall size of segment tree with array N - self.lazy = [0 for i in range(0,4*N)] # create array to store lazy update - self.flag = [0 for i in range(0,4*N)] # flag for lazy update + self.st = [0 for _ in range(0,4*N)] + self.lazy = [0 for _ in range(0,4*N)] + self.flag = [0 for _ in range(0,4*N)] def left(self, idx): return idx*2 @@ -71,9 +71,7 @@ def query(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max of [a,b] return max(q1,q2) def showData(self): - showList = [] - for i in range(1,N+1): - showList += [self.query(1, 1, self.N, i, i)] + showList = [self.query(1, 1, self.N, i, i) for i in range(1,N+1)] print (showList) diff --git a/data_structures/binary tree/segment_tree.py b/data_structures/binary tree/segment_tree.py index 001bf99..030cae3 100644 --- a/data_structures/binary tree/segment_tree.py +++ b/data_structures/binary tree/segment_tree.py @@ -52,9 +52,7 @@ def query_recursive(self, idx, l, r, a, b): #query(1, 1, N, a, b) for query max return max(q1, q2) def showData(self): - showList = [] - for i in range(1,N+1): - showList += [self.query(i, i)] + showList = [self.query(i, i) for i in range(1,N+1)] print (showList) diff --git a/data_structures/hashing/hash_table.py b/data_structures/hashing/hash_table.py index f0de128..89e4140 100644 --- a/data_structures/hashing/hash_table.py +++ b/data_structures/hashing/hash_table.py @@ -19,8 +19,9 @@ def keys(self): return self._keys def balanced_factor(self): - return sum([1 for slot in self.values - if slot is not None]) / (self.size_table * self.charge_factor) + return sum(1 for slot in self.values if slot is not None) / ( + self.size_table * self.charge_factor + ) def hash_function(self, key): return key % self.size_table @@ -28,16 +29,14 @@ def hash_function(self, key): def _step_by_step(self, step_ord): print("step {0}".format(step_ord)) - print([i for i in range(len(self.values))]) + print(list(range(len(self.values)))) print(self.values) def bulk_insert(self, values): - i = 1 self.__aux_list = values - for value in values: + for i, value in enumerate(values, start=1): self.insert_data(value) self._step_by_step(i) - i += 1 def _set_value(self, key, data): self.values[key] = data @@ -70,10 +69,7 @@ def insert_data(self, data): if self.values[key] is None: self._set_value(key, data) - elif self.values[key] == data: - pass - - else: + elif self.values[key] != data: colision_resolution = self._colision_resolution(key, data) if colision_resolution is not None: self._set_value(colision_resolution, data) diff --git a/data_structures/hashing/hash_table_with_linked_list.py b/data_structures/hashing/hash_table_with_linked_list.py index 9689e4f..fe51472 100644 --- a/data_structures/hashing/hash_table_with_linked_list.py +++ b/data_structures/hashing/hash_table_with_linked_list.py @@ -12,12 +12,16 @@ def _set_value(self, key, data): self._keys[key] = self.values[key] def balanced_factor(self): - return sum([self.charge_factor - len(slot) for slot in self.values])\ - / self.size_table * self.charge_factor + return ( + sum(self.charge_factor - len(slot) for slot in self.values) + / self.size_table + ) * self.charge_factor def _colision_resolution(self, key, data=None): - if not (len(self.values[key]) == self.charge_factor - and self.values.count(None) == 0): + if ( + len(self.values[key]) != self.charge_factor + or self.values.count(None) != 0 + ): return key return super()._colision_resolution(key, data) diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 8a521bc..2ed4afd 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -13,17 +13,15 @@ def check_prime(number): return 2 elif number == special_non_primes[-1]: return 3 - - return all([number % i for i in range(2, number)]) + + return all(number % i for i in range(2, number)) def next_prime(value, factor=1, **kwargs): - value = factor * value - first_value_val = value - - while not check_prime(value): - value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1 - - if value == first_value_val: - return next_prime(value + 1, **kwargs) - return value + value = factor * value + first_value_val = value + + while not check_prime(value): + value += 1 if "desc" not in kwargs or kwargs["desc"] is not True else -1 + + return next_prime(value + 1, **kwargs) if value == first_value_val else value diff --git a/data_structures/hashing/quadratic_probing.py b/data_structures/hashing/quadratic_probing.py index f7a9ac1..0f7a0bd 100644 --- a/data_structures/hashing/quadratic_probing.py +++ b/data_structures/hashing/quadratic_probing.py @@ -12,13 +12,16 @@ def __init__(self, *args, **kwargs): def _colision_resolution(self, key, data=None): i = 1 - new_key = self.hash_function(key + i*i) + new_key = self.hash_function(key + i**2) while self.values[new_key] is not None \ - and self.values[new_key] != key: + and self.values[new_key] != key: i += 1 - new_key = self.hash_function(key + i*i) if not \ - self.balanced_factor() >= self.lim_charge else None + new_key = ( + self.hash_function(key + i**2) + if not self.balanced_factor() >= self.lim_charge + else None + ) if new_key is None: break diff --git a/data_structures/heap/heap.py b/data_structures/heap/heap.py index 39778f7..cfd20b7 100644 --- a/data_structures/heap/heap.py +++ b/data_structures/heap/heap.py @@ -14,29 +14,26 @@ def __init__(self): #Default constructor of heap class. self.currsize = 0 def leftChild(self,i): - if 2*i+1 < self.currsize: - return 2*i+1 - return None + return 2*i+1 if 2*i+1 < self.currsize else None def rightChild(self,i): - if 2*i+2 < self.currsize: - return 2*i+2 - return None + return 2*i+2 if 2*i+2 < self.currsize else None def maxHeapify(self,node): - if node < self.currsize: - m = node - lc = self.leftChild(node) - rc = self.rightChild(node) - if lc is not None and self.h[lc] > self.h[m]: - m = lc - if rc is not None and self.h[rc] > self.h[m]: - m = rc - if m!=node: - temp = self.h[node] - self.h[node] = self.h[m] - self.h[m] = temp - self.maxHeapify(m) + if node >= self.currsize: + return + m = node + lc = self.leftChild(node) + rc = self.rightChild(node) + if lc is not None and self.h[lc] > self.h[m]: + m = lc + if rc is not None and self.h[rc] > self.h[m]: + m = rc + if m!=node: + temp = self.h[node] + self.h[node] = self.h[m] + self.h[m] = temp + self.maxHeapify(m) def buildHeap(self,a): #This function is used to build the heap from the data container 'a'. self.currsize = len(a) @@ -56,14 +53,14 @@ def getMax(self): #This function is used to get maximum value from the heap. return None def heapSort(self): #This function is used to sort the heap. - size = self.currsize - while self.currsize-1 >= 0: - temp = self.h[0] - self.h[0] = self.h[self.currsize-1] - self.h[self.currsize-1] = temp - self.currsize -= 1 - self.maxHeapify(0) - self.currsize = size + size = self.currsize + while self.currsize >= 1: + temp = self.h[0] + self.h[0] = self.h[self.currsize-1] + self.h[self.currsize-1] = temp + self.currsize -= 1 + self.maxHeapify(0) + self.currsize = size def insert(self,data): #This function is used to insert data in the heap. self.h.append(data) diff --git a/data_structures/linked_list/__init__.py b/data_structures/linked_list/__init__.py index 6d50f23..da0dc73 100644 --- a/data_structures/linked_list/__init__.py +++ b/data_structures/linked_list/__init__.py @@ -13,10 +13,9 @@ def add(self, item): def remove(self): if self.is_empty(): return None - else: - item = self.head.item - self.head = self.head.next - return item + item = self.head.item + self.head = self.head.next + return item def is_empty(self): return self.head is None diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 75b1f88..75bc5f1 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -74,4 +74,4 @@ class Link: def __init__(self, x): self.value = x def displayLink(self): - print("{}".format(self.value), end=" ") + print(f"{self.value}", end=" ") diff --git a/data_structures/linked_list/swapNodes.py b/data_structures/linked_list/swapNodes.py index ce2543b..743d1a0 100644 --- a/data_structures/linked_list/swapNodes.py +++ b/data_structures/linked_list/swapNodes.py @@ -26,32 +26,31 @@ def swapNodes(self, d1, d2): prevD2 = None if d1 == d2: return - else: - # find d1 - D1 = self.head - while D1 is not None and D1.data != d1: - prevD1 = D1 - D1 = D1.next - # find d2 - D2 = self.head - while D2 is not None and D2.data != d2: - prevD2 = D2 - D2 = D2.next - if D1 is None and D2 is None: - return + # find d1 + D1 = self.head + while D1 is not None and D1.data != d1: + prevD1 = D1 + D1 = D1.next + # find d2 + D2 = self.head + while D2 is not None and D2.data != d2: + prevD2 = D2 + D2 = D2.next + if D1 is None and D2 is None: + return # if D1 is head - if prevD1 is not None: - prevD1.next = D2 - else: - self.head = D2 - # if D2 is head - if prevD2 is not None: - prevD2.next = D1 - else: - self.head = D1 - temp = D1.next - D1.next = D2.next - D2.next = temp + if prevD1 is None: + self.head = D2 + else: + prevD1.next = D2 + # if D2 is head + if prevD2 is not None: + prevD2.next = D1 + else: + self.head = D1 + temp = D1.next + D1.next = D2.next + D2.next = temp # swapping code ends here diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py index c8d0b41..ac41880 100644 --- a/data_structures/queue/queue_on_list.py +++ b/data_structures/queue/queue_on_list.py @@ -6,8 +6,7 @@ def __init__(self): self.front=0 def __str__(self): - printed = '<' + str(self.entries)[1:-1] + '>' - return printed + return f'<{str(self.entries)[1:-1]}>' """Enqueues {@code item} @param item @@ -32,7 +31,7 @@ def get(self): @param rotation number of times to rotate queue""" def rotate(self, rotation): - for i in range(rotation): + for _ in range(rotation): self.put(self.get()) """Enqueues {@code item} diff --git a/data_structures/queue/queue_on_pseudo_stack.py b/data_structures/queue/queue_on_pseudo_stack.py index b69fbcc..29f5fbc 100644 --- a/data_structures/queue/queue_on_pseudo_stack.py +++ b/data_structures/queue/queue_on_pseudo_stack.py @@ -5,8 +5,7 @@ def __init__(self): self.length = 0 def __str__(self): - printed = '<' + str(self.stack)[1:-1] + '>' - return printed + return f'<{str(self.stack)[1:-1]}>' """Enqueues {@code item} @param item @@ -31,7 +30,7 @@ def get(self): @param rotation number of times to rotate queue""" def rotate(self, rotation): - for i in range(rotation): + for _ in range(rotation): temp = self.stack[0] self.stack = self.stack[1:] self.put(temp) diff --git a/data_structures/stacks/__init__.py b/data_structures/stacks/__init__.py index f7e92ae..be26e95 100644 --- a/data_structures/stacks/__init__.py +++ b/data_structures/stacks/__init__.py @@ -18,6 +18,5 @@ def push(self, item): def pop(self): if self.is_empty(): return None - else: - self.top -= 1 - return self.stack[self.top] + self.top -= 1 + return self.stack[self.top] diff --git a/data_structures/stacks/balanced_parentheses.py b/data_structures/stacks/balanced_parentheses.py index 3229d19..856b041 100644 --- a/data_structures/stacks/balanced_parentheses.py +++ b/data_structures/stacks/balanced_parentheses.py @@ -22,4 +22,4 @@ def balanced_parentheses(parentheses): examples = ['((()))', '((())', '(()))'] print('Balanced parentheses demonstration:\n') for example in examples: - print(example + ': ' + str(balanced_parentheses(example))) + print(f'{example}: {str(balanced_parentheses(example))}') diff --git a/data_structures/stacks/infix_to_postfix_conversion.py b/data_structures/stacks/infix_to_postfix_conversion.py index 75211fe..27af28e 100644 --- a/data_structures/stacks/infix_to_postfix_conversion.py +++ b/data_structures/stacks/infix_to_postfix_conversion.py @@ -60,5 +60,5 @@ def infix_to_postfix(expression): expression = 'a+b*(c^d-e)^(f+g*h)-i' print('Infix to Postfix Notation demonstration:\n') - print('Infix notation: ' + expression) - print('Postfix notation: ' + infix_to_postfix(expression)) + print(f'Infix notation: {expression}') + print(f'Postfix notation: {infix_to_postfix(expression)}') diff --git a/data_structures/stacks/infix_to_prefix_conversion.py b/data_structures/stacks/infix_to_prefix_conversion.py index da5fc26..a8ff1eb 100644 --- a/data_structures/stacks/infix_to_prefix_conversion.py +++ b/data_structures/stacks/infix_to_prefix_conversion.py @@ -18,29 +18,27 @@ def infix_2_postfix(Infix): Stack = [] Postfix = [] priority = {'^':3, '*':2, '/':2, '%':2, '+':1, '-':1} # Priority of each operator - print_width = len(Infix) if(len(Infix)>7) else 7 + print_width = max(len(Infix), 7) # Print table header for output print('Symbol'.center(8), 'Stack'.center(print_width), 'Postfix'.center(print_width), sep = " | ") print('-'*(print_width*3+7)) for x in Infix: - if(x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix + if (x.isalpha() or x.isdigit()): Postfix.append(x) # if x is Alphabet / Digit, add it to Postfix elif(x == '('): Stack.append(x) # if x is "(" push to Stack elif(x == ')'): # if x is ")" pop stack until "(" is encountered while(Stack[-1] != '('): Postfix.append( Stack.pop() ) #Pop stack & add the content to Postfix Stack.pop() else: - if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack - else: - while( len(Stack) > 0 and priority[x] <= priority[Stack[-1]]): # while priority of x is not greater than priority of element in the stack + if Stack: + while Stack and priority[x] <= priority[Stack[-1]]: # while priority of x is not greater than priority of element in the stack Postfix.append( Stack.pop() ) # pop stack & add to Postfix - Stack.append(x) # push x to stack - + if(len(Stack)==0): Stack.append(x) #If stack is empty, push x to stack print(x.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format - while(len(Stack) > 0): # while stack is not empty + while Stack: # while stack is not empty Postfix.append( Stack.pop() ) # pop stack & add to Postfix print(' '.center(8), (''.join(Stack)).ljust(print_width), (''.join(Postfix)).ljust(print_width), sep = " | ") # Output in tabular format diff --git a/data_structures/stacks/next.py b/data_structures/stacks/next.py index bca8333..af46aca 100644 --- a/data_structures/stacks/next.py +++ b/data_structures/stacks/next.py @@ -3,14 +3,9 @@ def printNGE(arr): for i in range(0, len(arr), 1): - - next = -1 - for j in range(i+1, len(arr), 1): - if arr[i] < arr[j]: - next = arr[j] - break - - print(str(arr[i]) + " -- " + str(next)) + + next = next((arr[j] for j in range(i+1, len(arr), 1) if arr[i] < arr[j]), -1) + print(f"{str(arr[i])} -- {str(next)}") # Driver program to test above function arr = [11,13,21,3] diff --git a/data_structures/stacks/postfix_evaluation.py b/data_structures/stacks/postfix_evaluation.py index 1786e71..c7ee721 100644 --- a/data_structures/stacks/postfix_evaluation.py +++ b/data_structures/stacks/postfix_evaluation.py @@ -29,18 +29,18 @@ def Solve(Postfix): print('-'*(30+len(Postfix))) for x in Postfix: - if( x.isdigit() ): # if x in digit + if ( x.isdigit() ): # if x in digit Stack.append(x) # append x to stack - print(x.rjust(8), ('push('+x+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format + print(x.rjust(8), f'push({x})'.ljust(12), ','.join(Stack), sep = " | ") else: B = Stack.pop() # pop stack - print("".rjust(8), ('pop('+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format + print("".rjust(8), f'pop({B})'.ljust(12), ','.join(Stack), sep = " | ") A = Stack.pop() # pop stack - print("".rjust(8), ('pop('+A+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format + print("".rjust(8), f'pop({A})'.ljust(12), ','.join(Stack), sep = " | ") Stack.append( str(Opr[x](int(A), int(B))) ) # evaluate the 2 values poped from stack & push result to stack - print(x.rjust(8), ('push('+A+x+B+')').ljust(12), ','.join(Stack), sep = " | ") # output in tabular format + print(x.rjust(8), f'push({A}{x}{B})'.ljust(12), ','.join(Stack), sep = " | ") return int(Stack[0]) diff --git a/data_structures/stacks/stack.py b/data_structures/stacks/stack.py index 7f979d9..adc8f1a 100644 --- a/data_structures/stacks/stack.py +++ b/data_structures/stacks/stack.py @@ -59,11 +59,11 @@ class StackOverflowError(BaseException): stack.push(i) print('Stack demonstration:\n') - print('Initial stack: ' + str(stack)) - print('pop(): ' + str(stack.pop())) - print('After pop(), the stack is now: ' + str(stack)) - print('peek(): ' + str(stack.peek())) + print(f'Initial stack: {str(stack)}') + print(f'pop(): {str(stack.pop())}') + print(f'After pop(), the stack is now: {str(stack)}') + print(f'peek(): {str(stack.peek())}') stack.push(100) - print('After push(100), the stack is now: ' + str(stack)) - print('is_empty(): ' + str(stack.is_empty())) - print('size(): ' + str(stack.size())) + print(f'After push(100), the stack is now: {str(stack)}') + print(f'is_empty(): {str(stack.is_empty())}') + print(f'size(): {str(stack.size())}') diff --git a/data_structures/stacks/stock_span_problem.py b/data_structures/stacks/stock_span_problem.py index 9628864..40d8a02 100644 --- a/data_structures/stacks/stock_span_problem.py +++ b/data_structures/stacks/stock_span_problem.py @@ -9,28 +9,26 @@ from __future__ import print_function def calculateSpan(price, S): - n = len(price) - # Create a stack and push index of fist element to it - st = [] - st.append(0) - + n = len(price) + # Create a stack and push index of fist element to it + st = [0] # Span value of first element is always 1 S[0] = 1 - - # Calculate span values for rest of the elements + + # Calculate span values for rest of the elements for i in range(1, n): # Pop elements from stack whlie stack is not - # empty and top of stack is smaller than price[i] - while( len(st) > 0 and price[st[0]] <= price[i]): + # empty and top of stack is smaller than price[i] + while st and price[st[0]] <= price[i]: st.pop() - + # If stack becomes empty, then price[i] is greater # than all elements on left of it, i.e. price[0], # price[1], ..price[i-1]. Else the price[i] is # greater than elements after top of stack S[i] = i+1 if len(st) <= 0 else (i - st[0]) - + # Push this element to stack st.append(i) @@ -42,11 +40,11 @@ def printArray(arr, n): # Driver program to test above function -price = [10, 4, 5, 90, 120, 80] -S = [0 for i in range(len(price)+1)] - +price = [10, 4, 5, 90, 120, 80] +S = [0 for _ in range(len(price)+1)] + # Fill the span values in array S[] calculateSpan(price, S) - + # Print the calculated span values printArray(S, len(price)) diff --git a/data_structures/union_find/union_find.py b/data_structures/union_find/union_find.py index 40eea67..9a617f2 100644 --- a/data_structures/union_find/union_find.py +++ b/data_structures/union_find/union_find.py @@ -22,10 +22,10 @@ def __init__(self, size): # in range [0, size]. It makes more sense. # Every set begins with only itself - self.root = [i for i in range(size+1)] + self.root = list(range(size+1)) # This is used for heuristic union by rank - self.weight = [0 for i in range(size+1)] + self.weight = [0 for _ in range(size+1)] def union(self, u, v): """ diff --git a/dynamic_programming/bitmask.py b/dynamic_programming/bitmask.py index 213b22f..dd447c9 100644 --- a/dynamic_programming/bitmask.py +++ b/dynamic_programming/bitmask.py @@ -17,13 +17,13 @@ class AssignmentUsingBitmask: def __init__(self,task_performed,total): self.total_tasks = total #total no of tasks (N) - + # DP table will have a dimension of (2^M)*N # initially all values are set to -1 - self.dp = [[-1 for i in range(total+1)] for j in range(2**len(task_performed))] - + self.dp = [[-1 for _ in range(total+1)] for _ in range(2**len(task_performed))] + self.task = defaultdict(list) #stores the list of persons for each task - + #finalmask is used to check if all persons are included by setting all bits to 1 self.finalmask = (1<=right_sum and left_sum>=cross_sum: - return left_low,left_high,left_sum - elif right_sum>=left_sum and right_sum>=cross_sum : - return right_low,right_high,right_sum - else: - return cross_left,cross_right,cross_sum + mid=(low+high)//2 + left_low,left_high,left_sum=find_max_sub_array(A,low,mid) + right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high) + cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high) + if left_sum>=right_sum and left_sum>=cross_sum: + return left_low,left_high,left_sum + elif right_sum>=left_sum and right_sum>=cross_sum : + return right_low,right_high,right_sum + else: + return cross_left,cross_right,cross_sum def find_max_cross_sum(A,low,mid,high): left_sum,max_left=-999999999,-1 @@ -43,16 +42,17 @@ def find_max_cross_sum(A,low,mid,high): inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000] tim=[] for i in inputs: - li=[randint(1,i) for j in range(i)] + li = [randint(1,i) for _ in range(i)] strt=time.time() (find_max_sub_array(li,0,len(li)-1)) end=time.time() tim.append(end-strt) - print("No of Inputs Time Taken") + print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i],'\t\t',tim[i]) plt.plot(inputs,tim) - plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ") + plt.xlabel("Number of Inputs") + plt.ylabel("Time taken in seconds ") plt.show() diff --git a/dynamic_programming/minimum_partition.py b/dynamic_programming/minimum_partition.py index 18aa1fa..751f209 100644 --- a/dynamic_programming/minimum_partition.py +++ b/dynamic_programming/minimum_partition.py @@ -5,7 +5,7 @@ def findMin(arr): n = len(arr) s = sum(arr) - dp = [[False for x in range(s+1)]for y in range(n+1)] + dp = [[False for _ in range(s+1)] for _ in range(n+1)] for i in range(1, n+1): dp[i][0] = True diff --git a/dynamic_programming/rod_cutting.py b/dynamic_programming/rod_cutting.py index 34350cb..eebcc59 100644 --- a/dynamic_programming/rod_cutting.py +++ b/dynamic_programming/rod_cutting.py @@ -24,7 +24,7 @@ def CutRod(n): return prices[1] noCut = prices[n] #The price you get when you don't cut the rod - yesCut = [-1 for x in range(n)] #The prices for the different cutting options + yesCut = [-1 for _ in range(n)] for i in range(1,n): if(solutions[i] == -1): @@ -53,6 +53,6 @@ def CutRod(n): length = 5 #The first price, 0, is for when we have no rod. prices = [0, 1, 3, 7, 9, 11, 13, 17, 21, 21, 30] -solutions = [-1 for x in range(length+1)] +solutions = [-1 for _ in range(length+1)] print(CutRod(length)) diff --git a/file_transfer_protocol/ftp_client_server.py b/file_transfer_protocol/ftp_client_server.py index 414c336..4100b05 100644 --- a/file_transfer_protocol/ftp_client_server.py +++ b/file_transfer_protocol/ftp_client_server.py @@ -18,12 +18,9 @@ filename = 'mytext.txt' with open(filename, 'rb') as f: - in_data = f.read(1024) - while in_data: + while in_data := f.read(1024): conn.send(in_data) print('Sent ', repr(in_data)) - in_data = f.read(1024) - print('Done sending') conn.send('Thank you for connecting') conn.close() diff --git a/file_transfer_protocol/ftp_send_receive.py b/file_transfer_protocol/ftp_send_receive.py index 6a9819e..a408876 100644 --- a/file_transfer_protocol/ftp_send_receive.py +++ b/file_transfer_protocol/ftp_send_receive.py @@ -21,7 +21,7 @@ def ReceiveFile(): FileName = 'example.txt' """ Enter the location of the file """ with open(FileName, 'wb') as LocalFile: - ftp.retrbinary('RETR ' + FileName, LocalFile.write, 1024) + ftp.retrbinary(f'RETR {FileName}', LocalFile.write, 1024) ftp.quit() """ @@ -32,5 +32,5 @@ def ReceiveFile(): def SendFile(): FileName = 'example.txt' """ Enter the name of the file """ with open(FileName, 'rb') as LocalFile: - ftp.storbinary('STOR ' + FileName, LocalFile) + ftp.storbinary(f'STOR {FileName}', LocalFile) ftp.quit() diff --git a/hashes/chaos_machine.py b/hashes/chaos_machine.py index f0a305b..43935c2 100644 --- a/hashes/chaos_machine.py +++ b/hashes/chaos_machine.py @@ -100,7 +100,8 @@ def reset(): inp = "" # Pulling Data (Output) -while inp in ("e", "E"): - print("%s" % format(pull(), '#04x')) - print(buffer_space); print(params_space) +while inp in {"e", "E"}: + print(f"{format(pull(), '#04x')}") + print(buffer_space) + print(params_space) inp = input("(e)exit? ").strip() diff --git a/hashes/md5.py b/hashes/md5.py index d3f1551..be2b8fa 100644 --- a/hashes/md5.py +++ b/hashes/md5.py @@ -17,10 +17,7 @@ def rearrange(bitString32): if len(bitString32) != 32: raise ValueError("Need length 32") - newString = "" - for i in [3,2,1,0]: - newString += bitString32[8*i:8*i+8] - return newString + return "".join(bitString32[8*i:8*i+8] for i in [3,2,1,0]) def reformatHex(i): """[summary] @@ -31,10 +28,7 @@ def reformatHex(i): """ hexrep = format(i,'08x') - thing = "" - for i in [3,2,1,0]: - thing += hexrep[2*i:2*i+2] - return thing + return "".join(hexrep[2*i:2*i+2] for i in [3,2,1,0]) def pad(bitString): """[summary] @@ -68,17 +62,12 @@ def getBlock(bitString): currPos = 0 while currPos < len(bitString): currPart = bitString[currPos:currPos+512] - mySplits = [] - for i in range(16): - mySplits.append(int(rearrange(currPart[32*i:32*i+32]),2)) - yield mySplits + yield [int(rearrange(currPart[32*i:32*i+32]),2) for i in range(16)] currPos += 512 def not32(i): i_str = format(i,'032b') - new_str = '' - for c in i_str: - new_str += '1' if c=='0' else '0' + new_str = ''.join('1' if c=='0' else '0' for c in i_str) return int(new_str,2) def sum32(a,b): @@ -95,9 +84,7 @@ def md5me(testString): testString {[string]} -- [message] """ - bs ='' - for i in testString: - bs += format(ord(i),'08b') + bs = ''.join(format(ord(i),'08b') for i in testString) bs = pad(bs) tvals = [int(2**32 * abs(math.sin(i+1))) for i in range(64)] @@ -142,8 +129,7 @@ def md5me(testString): c0 = sum32(c0, C) d0 = sum32(d0, D) - digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0) - return digest + return reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0) def test(): assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e" diff --git a/hashes/sha1.py b/hashes/sha1.py index 4c78ad3..2c2feaf 100644 --- a/hashes/sha1.py +++ b/hashes/sha1.py @@ -55,8 +55,7 @@ def padding(self): Pads the input message with zeros so that padded_data has 64 bytes or 512 bits """ padding = b'\x80' + b'\x00'*(63 - (len(self.data) + 8) % 64) - padded_data = self.data + padding + struct.pack('>Q', 8 * len(self.data)) - return padded_data + return self.data + padding + struct.pack('>Q', 8 * len(self.data)) def split_blocks(self): """ @@ -134,12 +133,12 @@ def main(): help='Hash the string') parser.add_argument('--file', dest='input_file', help='Hash contents of a file') args = parser.parse_args() - input_string = args.input_string #In any case hash input should be a bytestring if args.input_file: with open(args.input_file, 'rb') as f: hash_input = f.read() else: + input_string = args.input_string hash_input = bytes(input_string, 'utf-8') print(SHA1Hash(hash_input).final_hash()) diff --git a/linear_algebra_python/src/lib.py b/linear_algebra_python/src/lib.py index 281991a..351f186 100644 --- a/linear_algebra_python/src/lib.py +++ b/linear_algebra_python/src/lib.py @@ -84,9 +84,7 @@ def eulidLength(self): """ returns the eulidean length of the vector """ - summe = 0 - for c in self.__components: - summe += c**2 + summe = sum(c**2 for c in self.__components) return math.sqrt(summe) def __add__(self,other): """ @@ -108,8 +106,7 @@ def __sub__(self,other): """ size = len(self) if size == len(other): - result = [self.__components[i] - other.component(i) for i in range(size)] - return result + return [self.__components[i] - other.component(i) for i in range(size)] else: # error case raise Exception("must have the same size") def __mul__(self,other): @@ -117,15 +114,11 @@ def __mul__(self,other): mul implements the scalar multiplication and the dot-product """ - if isinstance(other,float) or isinstance(other,int): - ans = [c*other for c in self.__components] - return ans + if isinstance(other, (float, int)): + return [c*other for c in self.__components] elif (isinstance(other,Vector) and (len(self) == len(other))): size = len(self) - summe = 0 - for i in range(size): - summe += self.__components[i] * other.component(i) - return summe + return sum(self.__components[i] * other.component(i) for i in range(size)) else: # error case raise Exception("invalide operand!") def copy(self): @@ -171,8 +164,11 @@ def axpy(scalar,x,y): computes the axpy operation """ # precondition - assert(isinstance(x,Vector) and (isinstance(y,Vector)) \ - and (isinstance(scalar,int) or isinstance(scalar,float))) + assert ( + isinstance(x, Vector) + and (isinstance(y, Vector)) + and (isinstance(scalar, (int, float))) + ) return (x*scalar + y) @@ -184,7 +180,7 @@ def randomVector(N,a,b): random integer components between 'a' and 'b'. """ random.seed(None) - ans = [random.randint(a,b) for i in range(N)] + ans = [random.randint(a,b) for _ in range(N)] return Vector(ans) @@ -223,7 +219,7 @@ def __str__(self): ans += "|" for j in range(self.__width): if j < self.__width -1: - ans += str(self.__matrix[i][j]) + "," + ans += f"{str(self.__matrix[i][j])}," else: ans += str(self.__matrix[i][j]) + "|\n" return ans @@ -259,55 +255,49 @@ def __mul__(self,other): implements the matrix-scalar multiplication """ if isinstance(other, Vector): # vector-matrix - if (len(other) == self.__width): - ans = zeroVector(self.__height) - for i in range(self.__height): - summe = 0 - for j in range(self.__width): - summe += other.component(j) * self.__matrix[i][j] - ans.changeComponent(i,summe) - summe = 0 - return ans - else: + if len(other) != self.__width: raise Exception("vector must have the same size as the " + "number of columns of the matrix!") - elif isinstance(other,int) or isinstance(other,float): # matrix-scalar + ans = zeroVector(self.__height) + for i in range(self.__height): + summe = sum( + other.component(j) * self.__matrix[i][j] + for j in range(self.__width) + ) + ans.changeComponent(i,summe) + summe = 0 + return ans + elif isinstance(other, (int, float)): # matrix-scalar matrix = [[self.__matrix[i][j] * other for j in range(self.__width)] for i in range(self.__height)] return Matrix(matrix,self.__width,self.__height) def __add__(self,other): """ implements the matrix-addition. """ - if (self.__width == other.width() and self.__height == other.height()): - matrix = [] - for i in range(self.__height): - row = [] - for j in range(self.__width): - row.append(self.__matrix[i][j] + other.component(i,j)) - matrix.append(row) - return Matrix(matrix,self.__width,self.__height) - else: + if self.__width != other.width() or self.__height != other.height(): raise Exception("matrix must have the same dimension!") + matrix = [] + for i in range(self.__height): + row = [self.__matrix[i][j] + other.component(i,j) for j in range(self.__width)] + matrix.append(row) + return Matrix(matrix,self.__width,self.__height) def __sub__(self,other): """ implements the matrix-subtraction. """ - if (self.__width == other.width() and self.__height == other.height()): - matrix = [] - for i in range(self.__height): - row = [] - for j in range(self.__width): - row.append(self.__matrix[i][j] - other.component(i,j)) - matrix.append(row) - return Matrix(matrix,self.__width,self.__height) - else: + if self.__width != other.width() or self.__height != other.height(): raise Exception("matrix must have the same dimension!") + matrix = [] + for i in range(self.__height): + row = [self.__matrix[i][j] - other.component(i,j) for j in range(self.__width)] + matrix.append(row) + return Matrix(matrix,self.__width,self.__height) def squareZeroMatrix(N): """ returns a square zero-matrix of dimension NxN """ - ans = [[0]*N for i in range(N)] + ans = [[0]*N for _ in range(N)] return Matrix(ans,N,N) @@ -317,7 +307,7 @@ def randomMatrix(W,H,a,b): between 'a' and 'b' """ random.seed(None) - matrix = [[random.randint(a,b) for j in range(W)] for i in range(H)] + matrix = [[random.randint(a,b) for _ in range(W)] for _ in range(H)] return Matrix(matrix,W,H) diff --git a/machine_learning/decision_tree.py b/machine_learning/decision_tree.py index 7184990..2ca5e99 100644 --- a/machine_learning/decision_tree.py +++ b/machine_learning/decision_tree.py @@ -131,9 +131,9 @@ def main(): predictions = np.array([tree.predict(x) for x in test_cases]) avg_error = np.mean((predictions - test_cases) ** 2) - print("Test values: " + str(test_cases)) - print("Predictions: " + str(predictions)) - print("Average error: " + str(avg_error)) + print(f"Test values: {str(test_cases)}") + print(f"Predictions: {str(predictions)}") + print(f"Average error: {str(avg_error)}") if __name__ == '__main__': diff --git a/machine_learning/gradient_descent.py b/machine_learning/gradient_descent.py index 6387d49..35d9a2e 100644 --- a/machine_learning/gradient_descent.py +++ b/machine_learning/gradient_descent.py @@ -31,9 +31,10 @@ def _hypothesis_value(data_input_tuple): It is not explicitly mentioned in input data.. But, ML hypothesis functions use it. So, we have to take care of it separately. Line 36 takes care of it. """ - hyp_val = 0 - for i in range(len(parameter_vector) - 1): - hyp_val += data_input_tuple[i]*parameter_vector[i+1] + hyp_val = sum( + data_input_tuple[i] * parameter_vector[i + 1] + for i in range(len(parameter_vector) - 1) + ) hyp_val += parameter_vector[0] return hyp_val @@ -71,13 +72,10 @@ def summation_of_cost_derivative(index, end=m): :return: Returns the summation of cost derivative Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ - summation_value = 0 - for i in range(end): - if index == -1: - summation_value += _error(i) - else: - summation_value += _error(i)*train_data[i][0][index] - return summation_value + return sum( + _error(i) if index == -1 else _error(i) * train_data[i][0][index] + for i in range(end) + ) def get_cost_derivative(index): @@ -86,8 +84,7 @@ def get_cost_derivative(index): :return: derivative wrt to that index Note: If index is -1, this means we are calculating summation wrt to biased parameter. """ - cost_derivative_value = summation_of_cost_derivative(index, m)/m - return cost_derivative_value + return summation_of_cost_derivative(index, m)/m def run_gradient_descent(): diff --git a/machine_learning/k_means_clust.py b/machine_learning/k_means_clust.py index 368739a..edaa210 100644 --- a/machine_learning/k_means_clust.py +++ b/machine_learning/k_means_clust.py @@ -57,16 +57,11 @@ def get_initial_centroids(data, k, seed=None): if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points - + # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) - - # Keep centroids as dense format, as many entries will be nonzero due to averaging. - # As long as at least one document in a cluster contains a word, - # it will carry a nonzero weight in the TF-IDF vector of the centroid. - centroids = data[rand_indices,:] - - return centroids + + return data[rand_indices,:] def centroid_pairwise_dist(X,centroids): return pairwise_distances(X,centroids,metric='euclidean') @@ -76,12 +71,8 @@ def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data,centroids) - - # Compute cluster assignments for each data point: - # Fill in the blank (RHS only) - cluster_assignment = np.argmin(distances_from_centroids,axis=1) - - return cluster_assignment + + return np.argmin(distances_from_centroids,axis=1) def revise_centroids(data, k, cluster_assignment): new_centroids = [] @@ -91,9 +82,7 @@ def revise_centroids(data, k, cluster_assignment): # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) - new_centroids = np.array(new_centroids) - - return new_centroids + return np.array(new_centroids) def compute_heterogeneity(data, k, centroids, cluster_assignment): @@ -162,12 +151,3 @@ def kmeans(data, k, initial_centroids, maxiter=500, record_heterogeneity=None, v return centroids, cluster_assignment # Mock test below -if False: # change to true to run this test case. - import sklearn.datasets as ds - dataset = ds.load_iris() - k = 3 - heterogeneity = [] - initial_centroids = get_initial_centroids(dataset['data'], k, seed=0) - centroids, cluster_assignment = kmeans(dataset['data'], k, initial_centroids, maxiter=400, - record_heterogeneity=heterogeneity, verbose=True) - plot_heterogeneity(heterogeneity, k) diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index 8c23f1f..1577fa6 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -27,8 +27,7 @@ def collect_dataset(): item = item.split(',') data.append(item) data.pop(0) # This is for removing the labels from the list - dataset = np.matrix(data) - return dataset + return np.matrix(data) def run_steep_gradient_descent(data_x, data_y, @@ -62,8 +61,7 @@ def sum_of_square_error(data_x, data_y, len_data, theta): prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) - error = sum_elem / (2 * len_data) - return error + return sum_elem / (2 * len_data) def run_linear_regression(data_x, data_y): diff --git a/machine_learning/perceptron.py b/machine_learning/perceptron.py index fe1032a..0f73bcb 100644 --- a/machine_learning/perceptron.py +++ b/machine_learning/perceptron.py @@ -29,8 +29,8 @@ def trannig(self): for sample in self.sample: sample.insert(0, self.bias) - for i in range(self.col_sample): - self.weight.append(random.random()) + for _ in range(self.col_sample): + self.weight.append(random.random()) self.weight.insert(0, self.bias) diff --git a/machine_learning/scoring_functions.py b/machine_learning/scoring_functions.py index a2d97b0..d247dd4 100755 --- a/machine_learning/scoring_functions.py +++ b/machine_learning/scoring_functions.py @@ -20,9 +20,7 @@ def mae(predict, actual): actual = np.array(actual) difference = abs(predict - actual) - score = difference.mean() - - return score + return difference.mean() #Mean Squared Error def mse(predict, actual): @@ -32,8 +30,7 @@ def mse(predict, actual): difference = predict - actual square_diff = np.square(difference) - score = square_diff.mean() - return score + return square_diff.mean() #Root Mean Squared Error def rmse(predict, actual): @@ -43,8 +40,7 @@ def rmse(predict, actual): difference = predict - actual square_diff = np.square(difference) mean_square_diff = square_diff.mean() - score = np.sqrt(mean_square_diff) - return score + return np.sqrt(mean_square_diff) #Root Mean Square Logarithmic Error def rmsle(predict, actual): @@ -58,9 +54,7 @@ def rmsle(predict, actual): square_diff = np.square(difference) mean_square_diff = square_diff.mean() - score = np.sqrt(mean_square_diff) - - return score + return np.sqrt(mean_square_diff) #Mean Bias Deviation def mbd(predict, actual): @@ -68,11 +62,9 @@ def mbd(predict, actual): actual = np.array(actual) difference = predict - actual - numerator = np.sum(difference) / len(predict) + numerator = np.sum(difference) / len(predict) denumerator = np.sum(actual) / len(predict) print(numerator) print(denumerator) - score = float(numerator) / denumerator * 100 - - return score + return float(numerator) / denumerator * 100 diff --git a/maths/basic_maths.py b/maths/basic_maths.py index 6e8c919..b9ee7cc 100644 --- a/maths/basic_maths.py +++ b/maths/basic_maths.py @@ -18,20 +18,20 @@ def primeFactors(n): def numberOfDivisors(n): div = 1 - + temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) - div = div * (temp) - + div *= temp + for i in range(3, int(math.sqrt(n))+1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div = div * (temp) - + return div def sumOfDivisors(n): diff --git a/maths/newton_raphson.py b/maths/newton_raphson.py index c08bced..5686a3d 100644 --- a/maths/newton_raphson.py +++ b/maths/newton_raphson.py @@ -34,10 +34,7 @@ def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=Fal break else: raise ValueError("Itheration limit reached, no converging solution found") - if logsteps: - #If logstep is true, then log intermediate steps - return a, error, steps - return a, error + return (a, error, steps) if logsteps else (a, error) if __name__ == '__main__': import matplotlib.pyplot as plt diff --git a/maths/segmented_sieve.py b/maths/segmented_sieve.py index 52ca6fb..01cf6f4 100644 --- a/maths/segmented_sieve.py +++ b/maths/segmented_sieve.py @@ -2,45 +2,39 @@ def sieve(n): in_prime = [] - start = 2 end = int(math.sqrt(n)) # Size of every segment temp = [True] * (end + 1) prime = [] - - while(start <= end): + + for start in range(2, end + 1): if temp[start] == True: in_prime.append(start) - for i in range(start*start, end+1, start): + for i in range(start**2, end+1, start): if temp[i] == True: temp[i] = False - start += 1 prime += in_prime - + low = end + 1 high = low + end - 1 - if high > n: - high = n - - while(low <= n): + high = min(high, n) + while (low <= n): temp = [True] * (high-low+1) for each in in_prime: - + t = math.floor(low / each) * each if t < low: t += each - + for j in range(t, high+1, each): temp[j - low] = False - + for j in range(len(temp)): if temp[j] == True: prime.append(j+low) - + low = high + 1 high = low + end - 1 - if high > n: - high = n - + high = min(high, n) return prime print(sieve(10**6)) \ No newline at end of file diff --git a/maths/sieve_of_eratosthenes.py b/maths/sieve_of_eratosthenes.py index 26c17fa..4897d03 100644 --- a/maths/sieve_of_eratosthenes.py +++ b/maths/sieve_of_eratosthenes.py @@ -4,20 +4,14 @@ def sieve(n): l = [True] * (n+1) prime = [] - start = 2 end = int(math.sqrt(n)) - while(start <= end): + for start in range(2, end + 1): if l[start] == True: prime.append(start) - for i in range(start*start, n+1, start): + for i in range(start**2, n+1, start): if l[i] == True: l[i] = False - start += 1 - - for j in range(end+1,n+1): - if l[j] == True: - prime.append(j) - + prime.extend(j for j in range(end+1,n+1) if l[j] == True) return prime print(sieve(n)) diff --git a/maths/simpson_rule.py b/maths/simpson_rule.py index 091c86c..df4b542 100644 --- a/maths/simpson_rule.py +++ b/maths/simpson_rule.py @@ -20,10 +20,8 @@ def method_2(boundary, steps): x_i = makePoints(a,b,h) y = 0.0 y += (h/3.0)*f(a) - cnt = 2 - for i in x_i: - y += (h/3)*(4-2*(cnt%2))*f(i) - cnt += 1 + for cnt, i in enumerate(x_i, start=2): + y += (h/3)*(4-2*(cnt%2))*f(i) y += (h/3.0)*f(b) return y @@ -34,8 +32,7 @@ def makePoints(a,b,h): x = x + h def f(x): #enter your function here - y = (x-0)*(x-0) - return y + return (x-0)*(x-0) def main(): a = 0.0 #Lower bound of integration diff --git a/maths/trapezoidal_rule.py b/maths/trapezoidal_rule.py index 52310c1..5a24cc5 100644 --- a/maths/trapezoidal_rule.py +++ b/maths/trapezoidal_rule.py @@ -31,8 +31,7 @@ def makePoints(a,b,h): x = x + h def f(x): #enter your function here - y = (x-0)*(x-0) - return y + return (x-0)*(x-0) def main(): a = 0.0 #Lower bound of integration diff --git a/matrix/matrix_multiplication_addition.py b/matrix/matrix_multiplication_addition.py index dd50db7..73177b5 100644 --- a/matrix/matrix_multiplication_addition.py +++ b/matrix/matrix_multiplication_addition.py @@ -3,10 +3,7 @@ def add(matrix_a, matrix_b): columns = len(matrix_a[0]) matrix_c = [] for i in range(rows): - list_1 = [] - for j in range(columns): - val = matrix_a[i][j] + matrix_b[i][j] - list_1.append(val) + list_1 = [matrix_a[i][j] + matrix_b[i][j] for j in range(columns)] matrix_c.append(list_1) return matrix_c @@ -34,16 +31,15 @@ def transpose(matrix): def minor(matrix, row, column): minor = matrix[:row] + matrix[row + 1:] - minor = [row[:column] + row[column + 1:] for row in minor] - return minor + return [row[:column] + row[column + 1:] for row in minor] def determinant(matrix): if len(matrix) == 1: return matrix[0][0] - - res = 0 - for x in range(len(matrix)): - res += matrix[0][x] * determinant(minor(matrix , 0 , x)) * (-1) ** x - return res + + return sum( + matrix[0][x] * determinant(minor(matrix, 0, x)) * (-1) ** x + for x in range(len(matrix)) + ) def inverse(matrix): det = determinant(matrix) diff --git a/matrix/searching_in_sorted_matrix.py b/matrix/searching_in_sorted_matrix.py index 54913b3..ec14843 100644 --- a/matrix/searching_in_sorted_matrix.py +++ b/matrix/searching_in_sorted_matrix.py @@ -2,13 +2,13 @@ def search_in_a_sorted_matrix(mat, m, n, key): i, j = m - 1, 0 while i >= 0 and j < n: if key == mat[i][j]: - print('Key %s found at row- %s column- %s' % (key, i + 1, j + 1)) + print(f'Key {key} found at row- {i + 1} column- {j + 1}') return if key < mat[i][j]: i -= 1 else: j += 1 - print('Key %s not found' % (key)) + print(f'Key {key} not found') def main(): diff --git a/networking_flow/ford_fulkerson.py b/networking_flow/ford_fulkerson.py index d51f1f0..f3e473a 100644 --- a/networking_flow/ford_fulkerson.py +++ b/networking_flow/ford_fulkerson.py @@ -8,10 +8,9 @@ def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False]*len(graph) - queue=[] - queue.append(s) + queue = [s] visited[s] = True - + while queue: u = queue.pop(0) for ind in range(len(graph[u])): @@ -20,7 +19,7 @@ def BFS(graph, s, t, parent): visited[ind] = True parent[ind] = u - return True if visited[t] else False + return bool(visited[t]) def FordFulkerson(graph, source, sink): # This array is filled by BFS and to store path diff --git a/networking_flow/minimum_cut.py b/networking_flow/minimum_cut.py index 8ad6e03..bdaa0a6 100644 --- a/networking_flow/minimum_cut.py +++ b/networking_flow/minimum_cut.py @@ -3,10 +3,9 @@ def BFS(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False]*len(graph) - queue=[] - queue.append(s) + queue = [s] visited[s] = True - + while queue: u = queue.pop(0) for ind in range(len(graph[u])): @@ -15,12 +14,12 @@ def BFS(graph, s, t, parent): visited[ind] = True parent[ind] = u - return True if visited[t] else False + return bool(visited[t]) def mincut(graph, source, sink): # This array is filled by BFS and to store path parent = [-1]*(len(graph)) - max_flow = 0 + max_flow = 0 res = [] temp = [i[:] for i in graph] # Record orignial cut, copy. while BFS(graph, source, sink, parent) : @@ -34,7 +33,7 @@ def mincut(graph, source, sink): max_flow += path_flow v = sink - + while(v != source): u = parent[v] graph[u][v] -= path_flow @@ -42,10 +41,11 @@ def mincut(graph, source, sink): v = parent[v] for i in range(len(graph)): - for j in range(len(graph[0])): - if graph[i][j] == 0 and temp[i][j] > 0: - res.append((i,j)) - + res.extend( + (i, j) + for j in range(len(graph[0])) + if graph[i][j] == 0 and temp[i][j] > 0 + ) return res graph = [[0, 16, 13, 0, 0, 0], diff --git a/neural_network/bpnn.py b/neural_network/bpnn.py index 92deaee..f5ca2c0 100644 --- a/neural_network/bpnn.py +++ b/neural_network/bpnn.py @@ -54,12 +54,10 @@ def initializer(self,back_units): self.activation = sigmoid def cal_gradient(self): - if self.activation == sigmoid: - gradient_mat = np.dot(self.output ,(1- self.output).T) - gradient_activation = np.diag(np.diag(gradient_mat)) - else: - gradient_activation = 1 - return gradient_activation + if self.activation != sigmoid: + return 1 + gradient_mat = np.dot(self.output ,(1- self.output).T) + return np.diag(np.diag(gradient_mat)) def forward_propagation(self,xdata): self.xdata = xdata @@ -126,7 +124,7 @@ def train(self,xdata,ydata,train_round,accuracy): self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) - for round_i in range(train_round): + for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row,:]).T diff --git a/neural_network/convolution_neural_network.py b/neural_network/convolution_neural_network.py index 0dca2bc..941abb9 100644 --- a/neural_network/convolution_neural_network.py +++ b/neural_network/convolution_neural_network.py @@ -40,7 +40,10 @@ def __init__(self,conv1_get,size_p1,bp_num1,bp_num2,bp_num3,rate_w=0.2,rate_t=0. self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t - self.w_conv1 = [np.mat(-1*np.random.rand(self.conv1[0],self.conv1[0])+0.5) for i in range(self.conv1[1])] + self.w_conv1 = [ + np.mat(-1 * np.random.rand(self.conv1[0], self.conv1[0]) + 0.5) + for _ in range(self.conv1[1]) + ] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1*np.random.rand(self.num_bp2, self.num_bp1)+0.5) self.thre_conv1 = -2*np.random.rand(self.conv1[1])+1 @@ -68,7 +71,7 @@ def save_model(self,save_path): with open(save_path, 'wb') as f: pickle.dump(model_dic, f) - print('Model saved: %s'% save_path) + print(f'Model saved: {save_path}') @classmethod def ReadModel(cls,model_path): @@ -119,8 +122,8 @@ def convolute(self,data,convs,w_convs,thre_convs,conv_step): Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] - for i_focus in range(len(data_focus)): - net_focus = np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] + for data_focu in data_focus: + net_focus = np.sum(np.multiply(data_focu, w_convs[i_map])) - thre_convs[i_map] featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape(Size_FeatureMap, Size_FeatureMap) data_featuremap.append(featuremap) @@ -161,15 +164,13 @@ def _expand(self,datas): data_listed = datas[i].reshape(1,shapes[0]*shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) - data_expanded = np.asarray(data_expanded) - return data_expanded + return np.asarray(data_expanded) def _expand_mat(self,data_mat): #expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) - data_expanded = data_mat.reshape(1,shapes[0]*shapes[1]) - return data_expanded + return data_mat.reshape(1,shapes[0]*shapes[1]) def _calculate_gradient_from_pool(self,out_map,pd_pool,num_map,size_map,size_pooling): ''' @@ -251,7 +252,7 @@ def trian(self,patterns,datas_train, datas_teach, n_repeat, error_accuracy,draw_ alle = alle + errors #print(' ----Teach ',data_teach) #print(' ----BP_output ',bp_out3) - rp = rp + 1 + rp += 1 mse = alle/patterns all_mse.append(mse) def draw_error(): @@ -262,6 +263,7 @@ def draw_error(): plt.ylabel('All_mse') plt.grid(True, alpha=0.5) plt.show() + print('------------------Training Complished---------------------') print((' - - Training epoch: ', rp, ' - - Mse: %.6f' % mse)) if draw_e: @@ -300,7 +302,6 @@ def convolution(self,data): if __name__ == '__main__': - pass ''' I will put the example on other file ''' \ No newline at end of file diff --git a/neural_network/perceptron.py b/neural_network/perceptron.py index eb8b04e..547de3a 100644 --- a/neural_network/perceptron.py +++ b/neural_network/perceptron.py @@ -29,8 +29,8 @@ def training(self): for sample in self.sample: sample.insert(0, self.bias) - for i in range(self.col_sample): - self.weight.append(random.random()) + for _ in range(self.col_sample): + self.weight.append(random.random()) self.weight.insert(0, self.bias) diff --git a/other/anagrams.py b/other/anagrams.py index 29b34fb..134b3d0 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -4,8 +4,8 @@ start_time = time.time() print('creating word list...') path = os.path.split(os.path.realpath(__file__)) -with open(path[0] + '/words') as f: - word_list = sorted(list(set([word.strip().lower() for word in f]))) +with open(f'{path[0]}/words') as f: + word_list = sorted(list({word.strip().lower() for word in f})) def signature(word): return ''.join(sorted(word)) diff --git a/other/detecting_english_programmatically.py b/other/detecting_english_programmatically.py index 005fd3c..1e618af 100644 --- a/other/detecting_english_programmatically.py +++ b/other/detecting_english_programmatically.py @@ -6,7 +6,7 @@ def loadDictionary(): path = os.path.split(os.path.realpath(__file__)) englishWords = {} - with open(path[0] + '/Dictionary.txt') as dictionaryFile: + with open(f'{path[0]}/Dictionary.txt') as dictionaryFile: for word in dictionaryFile.read().split('\n'): englishWords[word] = None return englishWords @@ -21,18 +21,11 @@ def getEnglishCount(message): if possibleWords == []: return 0.0 - matches = 0 - for word in possibleWords: - if word in ENGLISH_WORDS: - matches += 1 - + matches = sum(1 for word in possibleWords if word in ENGLISH_WORDS) return float(matches) / len(possibleWords) def removeNonLetters(message): - lettersOnly = [] - for symbol in message: - if symbol in LETTERS_AND_SPACE: - lettersOnly.append(symbol) + lettersOnly = [symbol for symbol in message if symbol in LETTERS_AND_SPACE] return ''.join(lettersOnly) def isEnglish(message, wordPercentage = 20, letterPercentage = 85): diff --git a/other/euclidean_gcd.py b/other/euclidean_gcd.py index 30853e1..797c47e 100644 --- a/other/euclidean_gcd.py +++ b/other/euclidean_gcd.py @@ -9,11 +9,11 @@ def euclidean_gcd(a, b): return a def main(): - print("GCD(3, 5) = " + str(euclidean_gcd(3, 5))) - print("GCD(5, 3) = " + str(euclidean_gcd(5, 3))) - print("GCD(1, 3) = " + str(euclidean_gcd(1, 3))) - print("GCD(3, 6) = " + str(euclidean_gcd(3, 6))) - print("GCD(6, 3) = " + str(euclidean_gcd(6, 3))) + print(f"GCD(3, 5) = {str(euclidean_gcd(3, 5))}") + print(f"GCD(5, 3) = {str(euclidean_gcd(5, 3))}") + print(f"GCD(1, 3) = {str(euclidean_gcd(1, 3))}") + print(f"GCD(3, 6) = {str(euclidean_gcd(3, 6))}") + print(f"GCD(6, 3) = {str(euclidean_gcd(6, 3))}") if __name__ == '__main__': main() diff --git a/other/findingPrimes.py b/other/findingPrimes.py index 035a14f..b00df5b 100644 --- a/other/findingPrimes.py +++ b/other/findingPrimes.py @@ -8,14 +8,14 @@ from math import sqrt def SOE(n): check = round(sqrt(n)) #Need not check for multiples past the square root of n - - sieve = [False if i <2 else True for i in range(n+1)] #Set every index to False except for index 0 and 1 - + + sieve = [i >= 2 for i in range(n+1)] + for i in range(2, check): if(sieve[i] == True): #If i is a prime for j in range(i+i, n+1, i): #Step through the list in increments of i(the multiples of the prime) sieve[j] = False #Sets every multiple of i to False - + for i in range(n+1): if(sieve[i] == True): print(i, end=" ") diff --git a/other/fischer_yates_shuffle.py b/other/fischer_yates_shuffle.py index d87792f..b412d71 100644 --- a/other/fischer_yates_shuffle.py +++ b/other/fischer_yates_shuffle.py @@ -8,7 +8,7 @@ import random def FYshuffle(LIST): - for i in range(len(LIST)): + for _ in range(len(LIST)): a = random.randint(0, len(LIST)-1) b = random.randint(0, len(LIST)-1) LIST[a], LIST[b] = LIST[b], LIST[a] diff --git a/other/frequency_finder.py b/other/frequency_finder.py index 6264b25..bdb5c00 100644 --- a/other/frequency_finder.py +++ b/other/frequency_finder.py @@ -33,17 +33,14 @@ def getFrequencyOrder(message): else: freqToLetter[letterToFreq[letter]].append(letter) - for freq in freqToLetter: - freqToLetter[freq].sort(key = ETAOIN.find, reverse = True) + for freq, value in freqToLetter.items(): + value.sort(key = ETAOIN.find, reverse = True) freqToLetter[freq] = ''.join(freqToLetter[freq]) freqPairs = list(freqToLetter.items()) freqPairs.sort(key = getItemAtIndexZero, reverse = True) - freqOrder = [] - for freqPair in freqPairs: - freqOrder.append(freqPair[1]) - + freqOrder = [freqPair[1] for freqPair in freqPairs] return ''.join(freqOrder) def englishFreqMatchScore(message): @@ -52,11 +49,9 @@ def englishFreqMatchScore(message): 1 ''' freqOrder = getFrequencyOrder(message) - matchScore = 0 - for commonLetter in ETAOIN[:6]: - if commonLetter in freqOrder[:6]: - matchScore += 1 - + matchScore = sum( + 1 for commonLetter in ETAOIN[:6] if commonLetter in freqOrder[:6] + ) for uncommonLetter in ETAOIN[-6:]: if uncommonLetter in freqOrder[-6:]: matchScore += 1 diff --git a/other/game_of_life/game_o_life.py b/other/game_of_life/game_o_life.py index 1fdaa21..0065bb3 100644 --- a/other/game_of_life/game_o_life.py +++ b/other/game_of_life/game_o_life.py @@ -38,8 +38,7 @@ random.shuffle(choice) def create_canvas(size): - canvas = [ [False for i in range(size)] for j in range(size)] - return canvas + return [[False for _ in range(size)] for _ in range(size)] def seed(canvas): for i,row in enumerate(canvas): @@ -79,19 +78,16 @@ def __judge_point(pt,neighbours): # handling duplicate entry for focus pt. if pt : alive-=1 else : dead-=1 - + # running the rules of game here. state = pt - if pt: - if alive<2: - state=False - elif alive==2 or alive==3: - state=True - elif alive>3: + if state: + if alive < 2 or alive not in [2, 3] and alive > 3: state=False - else: - if alive==3: + elif alive in [2, 3]: state=True + elif alive==3: + state=True return state diff --git a/other/nested_brackets.py b/other/nested_brackets.py index 76677d5..4ab088b 100644 --- a/other/nested_brackets.py +++ b/other/nested_brackets.py @@ -19,8 +19,8 @@ def is_balanced(S): stack = [] - open_brackets = set({'(', '[', '{'}) - closed_brackets = set({')', ']', '}'}) + open_brackets = {'(', '[', '{'} + closed_brackets = {')', ']', '}'} open_to_closed = dict({'{':'}', '[':']', '(':')'}) for i in range(len(S)): @@ -29,10 +29,10 @@ def is_balanced(S): stack.append(S[i]) elif S[i] in closed_brackets: - if len(stack) == 0 or (len(stack) > 0 and open_to_closed[stack.pop()] != S[i]): + if not stack or stack and open_to_closed[stack.pop()] != S[i]: return False - return len(stack) == 0 + return not stack def main(): diff --git a/other/password_generator.py b/other/password_generator.py index 8916079..588469e 100644 --- a/other/password_generator.py +++ b/other/password_generator.py @@ -2,16 +2,18 @@ import string import random -letters = [letter for letter in string.ascii_letters] -digits = [digit for digit in string.digits] -symbols = [symbol for symbol in string.punctuation] +letters = list(string.ascii_letters) +digits = list(string.digits) +symbols = list(string.punctuation) chars = letters + digits + symbols random.shuffle(chars) min_length = 8 max_length = 16 -password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length))) -print('Password: ' + password) +password = ''.join( + random.choice(chars) + for _ in range(random.randint(min_length, max_length))) +print(f'Password: {password}') print('[ If you are thinking of using this passsword, You better save it. ]') diff --git a/other/primelib.py b/other/primelib.py index 19572f8..d39f556 100644 --- a/other/primelib.py +++ b/other/primelib.py @@ -83,27 +83,27 @@ def sieveEr(N): # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" - + # beginList: conatins all natural numbers from 2 upt to N - beginList = [x for x in range(2,N+1)] + beginList = list(range(2,N+1)) ans = [] # this list will be returns. - + # actual sieve of erathostenes for i in range(len(beginList)): - + for j in range(i+1,len(beginList)): - + if (beginList[i] != 0) and \ (beginList[j] % beginList[i] == 0): beginList[j] = 0 - + # filters actual prime numbers. ans = [x for x in beginList if x != 0] - + # precondition assert isinstance(ans,list), "'ans' must been from type list" - + return ans @@ -118,20 +118,11 @@ def getPrimeNumbers(N): # precondition assert isinstance(N,int) and (N > 2), "'N' must been an int and > 2" - - ans = [] - - # iterates over all numbers between 2 up to N+1 - # if a number is prime then appends to list 'ans' - for number in range(2,N+1): - - if isPrime(number): - - ans.append(number) - + + ans = [number for number in range(2,N+1) if isPrime(number)] # precondition assert isinstance(ans,list), "'ans' must been from type list" - + return ans @@ -144,11 +135,11 @@ def primeFactorization(number): """ import math # for function sqrt - + # precondition assert isinstance(number,int) and number >= 0, \ "'number' must been an int and >= 0" - + ans = [] # this list will be returns of the function. # potential prime number factors. @@ -156,29 +147,25 @@ def primeFactorization(number): factor = 2 quotient = number - - - if number == 0 or number == 1: - + + + if number in [0, 1] or number not in [0, 1] and isPrime(number): + ans.append(number) - - # if 'number' not prime then builds the prime factorization of 'number' - elif not isPrime(number): - + + else: + while (quotient != 1): - + if isPrime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 - - else: - ans.append(number) - + # precondition assert isinstance(ans,list), "'ans' must been from type list" - + return ans @@ -274,9 +261,9 @@ def goldbach(number): # precondition assert isinstance(number,int) and (number > 2) and isEven(number), \ "'number' must been an int, even and > 2" - + ans = [] # this list will returned - + # creates a list of prime numbers between 2 up to 'number' primeNumbers = getPrimeNumbers(number) lenPN = len(primeNumbers) @@ -284,31 +271,29 @@ def goldbach(number): # run variable for while-loops. i = 0 j = 1 - + # exit variable. for break up the loops loop = True - + while (i < lenPN and loop): j = i+1 - - + + while (j < lenPN and loop): if primeNumbers[i] + primeNumbers[j] == number: loop = False - ans.append(primeNumbers[i]) - ans.append(primeNumbers[j]) - + ans.extend((primeNumbers[i], primeNumbers[j])) j += 1 i += 1 - + # precondition assert isinstance(ans,list) and (len(ans) == 2) and \ (ans[0] + ans[1] == number) and isPrime(ans[0]) and isPrime(ans[1]), \ "'ans' must contains two primes. And sum of elements must been eq 'number'" - + return ans # ---------------------------------------------- @@ -352,65 +337,65 @@ def kgV(number1, number2): assert isinstance(number1,int) and isinstance(number2,int) \ and (number1 >= 1) and (number2 >= 1), \ "'number1' and 'number2' must been positive integer." - + ans = 1 # actual answer that will be return. - + # for kgV (x,1) if number1 > 1 and number2 > 1: - + # builds the prime factorization of 'number1' and 'number2' primeFac1 = primeFactorization(number1) primeFac2 = primeFactorization(number2) - + elif number1 == 1 or number2 == 1: - + primeFac1 = [] primeFac2 = [] ans = max(number1,number2) - + count1 = 0 count2 = 0 - + done = [] # captured numbers int both 'primeFac1' and 'primeFac2' - + # iterates through primeFac1 for n in primeFac1: if n not in done: - + if n in primeFac2: - + count1 = primeFac1.count(n) count2 = primeFac2.count(n) - - for i in range(max(count1,count2)): + + for _ in range(max(count1,count2)): ans *= n - + else: count1 = primeFac1.count(n) - - for i in range(count1): + + for _ in range(count1): ans *= n - + done.append(n) - + # iterates through primeFac2 for n in primeFac2: if n not in done: count2 = primeFac2.count(n) - - for i in range(count2): + + for _ in range(count2): ans *= n - + done.append(n) - + # precondition assert isinstance(ans,int) and (ans >= 0), \ "'ans' must been from type int and positive" - + return ans # ---------------------------------- @@ -458,31 +443,31 @@ def getPrimesBetween(pNumber1, pNumber2): # precondition assert isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2), \ "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" - + number = pNumber1 + 1 # jump to the next number - + ans = [] # this list will be returns. - + # if number is not prime then # fetch the next prime number. while not isPrime(number): number += 1 - + while number < pNumber2: - + ans.append(number) - + number += 1 - + # fetch the next prime number. while not isPrime(number): number += 1 - + # precondition - assert isinstance(ans,list) and ans[0] != pNumber1 \ - and ans[len(ans)-1] != pNumber2, \ - "'ans' must been a list without the arguments" - + assert ( + isinstance(ans, list) and ans[0] != pNumber1 and ans[-1] != pNumber2 + ), "'ans' must been a list without the arguments" + # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans @@ -498,20 +483,12 @@ def getDivisors(n): assert isinstance(n,int) and (n >= 1), "'n' must been int and >= 1" from math import sqrt - - ans = [] # will be returned. - - for divisor in range(1,n+1): - - if n % divisor == 0: - ans.append(divisor) - - + + ans = [divisor for divisor in range(1,n+1) if n % divisor == 0] #precondition - assert ans[0] == 1 and ans[len(ans)-1] == n, \ - "Error in function getDivisiors(...)" - - + assert ans[0] == 1 and ans[-1] == n, "Error in function getDivisiors(...)" + + return ans @@ -590,15 +567,14 @@ def fib(n): # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" - + tmp = 0 fib1 = 1 ans = 1 # this will be return - - for i in range(n-1): - + + for _ in range(n-1): tmp = ans ans += fib1 fib1 = tmp - + return ans diff --git a/project_euler/problem_01/sol5.py b/project_euler/problem_01/sol5.py index e261cc8..64b2b47 100644 --- a/project_euler/problem_01/sol5.py +++ b/project_euler/problem_01/sol5.py @@ -4,6 +4,7 @@ we get 3,5,6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below N. ''' + from __future__ import print_function try: input = raw_input #python3 @@ -12,5 +13,5 @@ """A straightforward pythonic solution using list comprehension""" n = int(input().strip()) -print(sum([i for i in range(n) if i%3==0 or i%5==0])) +print(sum(i for i in range(n) if i%3==0 or i%5==0)) diff --git a/project_euler/problem_03/sol1.py b/project_euler/problem_03/sol1.py index bb9f8ca..2e65755 100644 --- a/project_euler/problem_03/sol1.py +++ b/project_euler/problem_03/sol1.py @@ -13,18 +13,15 @@ def isprime(no): elif (no%2==0): return False sq = int(math.sqrt(no))+1 - for i in range(3,sq,2): - if(no%i==0): - return False - return True + return all(no%i != 0 for i in range(3, sq, 2)) maxNumber = 0 n=int(input()) -if(isprime(n)): +if (isprime(n)): print(n) else: while (n%2==0): - n=n/2 + n /= 2 if(isprime(n)): print(n) else: diff --git a/project_euler/problem_03/sol2.py b/project_euler/problem_03/sol2.py index 44f9c63..6e0b862 100644 --- a/project_euler/problem_03/sol2.py +++ b/project_euler/problem_03/sol2.py @@ -4,11 +4,12 @@ e.g. for 10, largest prime factor = 5. For 17, largest prime factor = 17. ''' + from __future__ import print_function n=int(input()) prime=1 i=2 -while(i*i<=n): +while i**2 <= n: while(n%i==0): prime=i n//=i diff --git a/project_euler/problem_05/sol1.py b/project_euler/problem_05/sol1.py index 7896d75..c121b71 100644 --- a/project_euler/problem_05/sol1.py +++ b/project_euler/problem_05/sol1.py @@ -3,17 +3,14 @@ 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible(divisible with no remainder) by all of the numbers from 1 to N? ''' + from __future__ import print_function n = int(input()) i = 0 while 1: i+=n*(n-1) - nfound=0 - for j in range(2,n): - if (i%j != 0): - nfound=1 - break + nfound = next((1 for j in range(2,n) if (i%j != 0)), 0) if(nfound==0): if(i==0): i=1 diff --git a/project_euler/problem_06/sol3.py b/project_euler/problem_06/sol3.py index b2d9f44..8a47697 100644 --- a/project_euler/problem_06/sol3.py +++ b/project_euler/problem_06/sol3.py @@ -10,7 +10,7 @@ from __future__ import print_function import math def problem6(number=100): - sum_of_squares = sum([i*i for i in range(1,number+1)]) + sum_of_squares = sum(i*i for i in range(1,number+1)) square_of_sum = int(math.pow(sum(range(1,number+1)),2)) return square_of_sum - sum_of_squares def main(): diff --git a/project_euler/problem_07/sol2.py b/project_euler/problem_07/sol2.py index fdf39cb..7251701 100644 --- a/project_euler/problem_07/sol2.py +++ b/project_euler/problem_07/sol2.py @@ -1,16 +1,11 @@ # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the Nth prime number? def isprime(number): - for i in range(2,int(number**0.5)+1): - if number%i==0: - return False - return True + return all(number%i != 0 for i in range(2, int(number**0.5)+1)) n = int(input('Enter The N\'th Prime Number You Want To Get: ')) # Ask For The N'th Prime Number Wanted primes = [] num = 2 while len(primes) < n: if isprime(num): primes.append(num) - num += 1 - else: - num += 1 -print(primes[len(primes) - 1]) + num += 1 +print(primes[-1]) diff --git a/project_euler/problem_08/sol2.py b/project_euler/problem_08/sol2.py index ae03f3a..96e4045 100644 --- a/project_euler/problem_08/sol2.py +++ b/project_euler/problem_08/sol2.py @@ -2,7 +2,12 @@ def main(): number=input().strip() - print(max([reduce(lambda x,y: int(x)*int(y),number[i:i+13]) for i in range(len(number)-12)])) + print( + max( + reduce(lambda x, y: int(x) * int(y), number[i : i + 13]) + for i in range(len(number) - 12) + ) + ) if __name__ == '__main__': main() diff --git a/project_euler/problem_09/sol2.py b/project_euler/problem_09/sol2.py index 933f5c5..b15a199 100644 --- a/project_euler/problem_09/sol2.py +++ b/project_euler/problem_09/sol2.py @@ -2,6 +2,7 @@ a^2+b^2=c^2 Given N, Check if there exists any Pythagorean triplet for which a+b+c=N Find maximum possible value of product of a,b,c among all such Pythagorean triplets, If there is no such Pythagorean triplet print -1.""" + #!/bin/python3 product=-1 @@ -9,7 +10,7 @@ N = int(input()) for a in range(1,N//3): """Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c """ - b=(N*N-2*a*N)//(2*N-2*a) + b = (N**2 - 2*a*N) // (2*N-2*a) c=N-a-b if c*c==(a*a+b*b): d=(a*b*c) diff --git a/project_euler/problem_10/sol1.py b/project_euler/problem_10/sol1.py index 94e5b73..b98a2eb 100644 --- a/project_euler/problem_10/sol1.py +++ b/project_euler/problem_10/sol1.py @@ -7,11 +7,7 @@ xrange = range #Python 3 def is_prime(n): - for i in xrange(2, int(sqrt(n))+1): - if n%i == 0: - return False - - return True + return all(n%i != 0 for i in xrange(2, int(sqrt(n))+1)) def sum_of_primes(n): if n > 2: diff --git a/project_euler/problem_11/sol1.py b/project_euler/problem_11/sol1.py index b882dc4..4b626fe 100644 --- a/project_euler/problem_11/sol1.py +++ b/project_euler/problem_11/sol1.py @@ -60,9 +60,7 @@ def largest_product(grid): if __name__ == '__main__': grid = [] with open('grid.txt') as file: - for line in file: - grid.append(line.strip('\n').split(' ')) - + grid.extend(line.strip('\n').split(' ') for line in file) grid = [[int(i) for i in grid[j]] for j in xrange(len(grid))] print(largest_product(grid)) \ No newline at end of file diff --git a/project_euler/problem_11/sol2.py b/project_euler/problem_11/sol2.py index b03395f..25ad0fd 100644 --- a/project_euler/problem_11/sol2.py +++ b/project_euler/problem_11/sol2.py @@ -1,9 +1,6 @@ def main(): with open ("grid.txt", "r") as f: - l = [] - for i in range(20): - l.append([int(x) for x in f.readline().split()]) - + l = [[int(x) for x in f.readline().split()] for _ in range(20)] maximum = 0 # right @@ -26,7 +23,7 @@ def main(): temp = l[i][j] * l[i+1][j+1] * l[i+2][j+2] * l[i+3][j+3] if temp > maximum: maximum = temp - + #diagonal 2 for i in range(17): for j in range(3, 20): diff --git a/project_euler/problem_12/sol2.py b/project_euler/problem_12/sol2.py index 479ab2b..de4430f 100644 --- a/project_euler/problem_12/sol2.py +++ b/project_euler/problem_12/sol2.py @@ -3,6 +3,6 @@ def triangle_number_generator(): yield n*(n+1)//2 def count_divisors(n): - return sum([2 for i in range(1,int(n**0.5)+1) if n%i==0 and i*i != n]) + return sum(2 for i in range(1,int(n**0.5)+1) if n%i==0 and i*i != n) print(next(i for i in triangle_number_generator() if count_divisors(i) > 500)) diff --git a/project_euler/problem_13/sol1.py b/project_euler/problem_13/sol1.py index faaaad5..b3d9edf 100644 --- a/project_euler/problem_13/sol1.py +++ b/project_euler/problem_13/sol1.py @@ -2,13 +2,11 @@ Problem Statement: Work out the first ten digits of the sum of the N 50-digit numbers. ''' + from __future__ import print_function n = int(input().strip()) -array = [] -for i in range(n): - array.append(int(input().strip())) - +array = [int(input().strip()) for _ in range(n)] print(str(sum(array))[:10]) diff --git a/project_euler/problem_14/sol1.py b/project_euler/problem_14/sol1.py index 9037f6e..3ad05bd 100644 --- a/project_euler/problem_14/sol1.py +++ b/project_euler/problem_14/sol1.py @@ -9,11 +9,9 @@ while number > 1: if number % 2 == 0: number /=2 - counter += 1 else: number = (3*number)+1 - counter += 1 - + counter += 1 if counter > pre_counter: largest_number = input1 pre_counter = counter diff --git a/project_euler/problem_14/sol2.py b/project_euler/problem_14/sol2.py index b9de42b..e7148e2 100644 --- a/project_euler/problem_14/sol2.py +++ b/project_euler/problem_14/sol2.py @@ -12,5 +12,5 @@ def collatz_sequence(n): sequence.append(n) return sequence -answer = max([(len(collatz_sequence(i)), i) for i in range(1,1000000)]) +answer = max((len(collatz_sequence(i)), i) for i in range(1,1000000)) print("Longest Collatz sequence under one million is %d with length %d" % (answer[1],answer[0])) \ No newline at end of file diff --git a/project_euler/problem_16/sol1.py b/project_euler/problem_16/sol1.py index 05c7916..7e55d2c 100644 --- a/project_euler/problem_16/sol1.py +++ b/project_euler/problem_16/sol1.py @@ -5,11 +5,7 @@ list_num = list(string_num) -sum_of_num = 0 - print("2 ^",power,"=",num) -for i in list_num: - sum_of_num += int(i) - +sum_of_num = sum(int(i) for i in list_num) print("Sum of the digits are:",sum_of_num) diff --git a/project_euler/problem_19/sol1.py b/project_euler/problem_19/sol1.py index 94cf117..0f02835 100644 --- a/project_euler/problem_19/sol1.py +++ b/project_euler/problem_19/sol1.py @@ -29,18 +29,17 @@ while year < 2001: day += 7 - if (year%4 == 0 and not year%100 == 0) or (year%400 == 0): + if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: if day > days_per_month[month-1] and month is not 2: month += 1 - day = day-days_per_month[month-2] + day -= days_per_month[month-2] elif day > 29 and month is 2: month += 1 day = day-29 - else: - if day > days_per_month[month-1]: - month += 1 - day = day-days_per_month[month-2] - + elif day > days_per_month[month-1]: + month += 1 + day = day-days_per_month[month-2] + if month > 12: year += 1 month = 1 diff --git a/project_euler/problem_20/sol2.py b/project_euler/problem_20/sol2.py index bca9af9..a7c6215 100644 --- a/project_euler/problem_20/sol2.py +++ b/project_euler/problem_20/sol2.py @@ -1,5 +1,5 @@ from math import factorial def main(): - print(sum([int(x) for x in str(factorial(100))])) + print(sum(int(x) for x in str(factorial(100)))) if __name__ == '__main__': main() \ No newline at end of file diff --git a/project_euler/problem_25/sol1.py b/project_euler/problem_25/sol1.py index f8cea30..e6c389f 100644 --- a/project_euler/problem_25/sol1.py +++ b/project_euler/problem_25/sol1.py @@ -12,9 +12,7 @@ def fibonacci(n): return 1 else: sequence = [0, 1] - for i in xrange(2, n+1): - sequence.append(sequence[i-1] + sequence[i-2]) - + sequence.extend(sequence[i-1] + sequence[i-2] for i in xrange(2, n+1)) return sequence[n] def fibonacci_digits_index(n): diff --git a/project_euler/problem_25/sol2.py b/project_euler/problem_25/sol2.py index 35147a9..e6977c3 100644 --- a/project_euler/problem_25/sol2.py +++ b/project_euler/problem_25/sol2.py @@ -7,4 +7,4 @@ def fibonacci_genrator(): gen = fibonacci_genrator() while len(str(next(gen))) < 1000: answer += 1 -assert answer+1 == 4782 +assert answer == 4781 diff --git a/project_euler/problem_36/sol1.py b/project_euler/problem_36/sol1.py index d78e7e5..932ee0d 100644 --- a/project_euler/problem_36/sol1.py +++ b/project_euler/problem_36/sol1.py @@ -16,15 +16,11 @@ def is_palindrome(n): n = str(n) - if n == n[::-1]: - return True - else: - return False - -total = 0 - -for i in xrange(1, 1000000): - if is_palindrome(i) and is_palindrome(bin(i).split('b')[1]): - total += i + return n == n[::-1] +total = sum( + i + for i in xrange(1, 1000000) + if is_palindrome(i) and is_palindrome(bin(i).split('b')[1]) +) print(total) \ No newline at end of file diff --git a/project_euler/problem_48/sol1.py b/project_euler/problem_48/sol1.py index 5c4bdb0..ffb348c 100644 --- a/project_euler/problem_48/sol1.py +++ b/project_euler/problem_48/sol1.py @@ -13,9 +13,5 @@ except NameError: xrange = range -total = 0 -for i in xrange(1, 1001): - total += i**i - - +total = sum(i**i for i in xrange(1, 1001)) print(str(total)[-10:]) \ No newline at end of file diff --git a/searches/binary_search.py b/searches/binary_search.py index 7df4588..a0f319b 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -49,11 +49,10 @@ def binary_search(sorted_collection, item): current_item = sorted_collection[midpoint] if current_item == item: return midpoint + if item < current_item: + right = midpoint - 1 else: - if item < current_item: - right = midpoint - 1 - else: - left = midpoint + 1 + left = midpoint + 1 return None @@ -156,6 +155,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') diff --git a/searches/interpolation_search.py b/searches/interpolation_search.py index db9893b..aa80701 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -22,7 +22,7 @@ def interpolation_search(sorted_collection, item): while left <= right: point = left + ((item - sorted_collection[left]) * (right - left)) // (sorted_collection[right] - sorted_collection[left]) - + #out of range check if point<0 or point>=len(sorted_collection): return None @@ -30,11 +30,10 @@ def interpolation_search(sorted_collection, item): current_item = sorted_collection[point] if current_item == item: return point + if item < current_item: + right = point - 1 else: - if item < current_item: - right = point - 1 - else: - left = point + 1 + left = point + 1 return None @@ -93,6 +92,6 @@ def __assert_sorted(collection): target = int(target_input) 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') diff --git a/searches/jump_search.py b/searches/jump_search.py index 10cb933..b392018 100644 --- a/searches/jump_search.py +++ b/searches/jump_search.py @@ -14,9 +14,7 @@ def jump_search(arr, x): prev = prev + 1 if prev == min(step, n): return -1 - if arr[prev] == x: - return prev - return -1 + return prev if arr[prev] == x else -1 diff --git a/searches/linear_search.py b/searches/linear_search.py index 058322f..d300c49 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -36,10 +36,9 @@ def linear_search(sequence, target): >>> linear_search([0, 5, 7, 10, 15], 6) """ - for index, item in enumerate(sequence): - if item == target: - return index - return None + return next( + (index for index, item in enumerate(sequence) if item == target), None + ) if __name__ == '__main__': @@ -50,6 +49,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') diff --git a/searches/sentinel_linear_search.py b/searches/sentinel_linear_search.py index 336cc5a..ccc4e58 100644 --- a/searches/sentinel_linear_search.py +++ b/searches/sentinel_linear_search.py @@ -38,10 +38,7 @@ def sentinel_linear_search(sequence, target): sequence.pop() - if index == len(sequence): - return None - - return index + return None if index == len(sequence) else index if __name__ == '__main__': @@ -57,6 +54,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') \ No newline at end of file diff --git a/searches/tabu_search.py b/searches/tabu_search.py index e21ddd5..11ce491 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -51,13 +51,12 @@ def generate_neighbours(path): with open(path) as f: for line in f: if line.split()[0] not in dict_of_neighbours: - _list = list() - _list.append([line.split()[1], line.split()[2]]) + _list = [[line.split()[1], line.split()[2]]] dict_of_neighbours[line.split()[0]] = _list else: dict_of_neighbours[line.split()[0]].append([line.split()[1], line.split()[2]]) if line.split()[1] not in dict_of_neighbours: - _list = list() + _list = [] _list.append([line.split()[0], line.split()[2]]) dict_of_neighbours[line.split()[1]] = _list else: @@ -186,7 +185,7 @@ def tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, """ count = 1 solution = first_solution - tabu_list = list() + tabu_list = [] best_cost = distance_of_first_solution best_solution_ever = solution @@ -197,7 +196,7 @@ def tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, best_cost_index = len(best_solution) - 1 found = False - while found is False: + while not found: i = 0 while i < len(best_solution): @@ -205,7 +204,7 @@ def tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, first_exchange_node = best_solution[i] second_exchange_node = solution[i] break - i = i + 1 + i += 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [second_exchange_node, first_exchange_node] not in tabu_list: @@ -223,7 +222,7 @@ def tabu_search(first_solution, distance_of_first_solution, dict_of_neighbours, if len(tabu_list) >= size: tabu_list.pop(0) - count = count + 1 + count += 1 return best_solution_ever, best_cost diff --git a/searches/ternary_search.py b/searches/ternary_search.py index c610f9b..9c97890 100644 --- a/searches/ternary_search.py +++ b/searches/ternary_search.py @@ -99,9 +99,9 @@ def __assert_sorted(collection): target = int(target_input) result1 = ite_ternary_search(collection, target) 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') diff --git a/simple_client/server.py b/simple_client/server.py index c230756..7fc1ae7 100644 --- a/simple_client/server.py +++ b/simple_client/server.py @@ -13,9 +13,9 @@ print('connected to:', addr) while 1: - data = conn.recv(1024).decode('ascii')#receive 1024 bytes and decode using ascii - if not data: - break - conn.send((data + ' [ addition by server ]').encode('ascii')) + if data := conn.recv(1024).decode('ascii'): + conn.send(f'{data} [ addition by server ]'.encode('ascii')) + else: + break conn.close() diff --git a/sorts/BitonicSort.py b/sorts/BitonicSort.py index bae95b4..5b5dec1 100644 --- a/sorts/BitonicSort.py +++ b/sorts/BitonicSort.py @@ -43,11 +43,8 @@ def sort(a, N, up): # Driver code to test above -a = [] - n = int(input()) -for i in range(n): - a.append(int(input())) +a = [int(input()) for _ in range(n)] up = 1 sort(a, n, up) diff --git a/sorts/bucket_sort.py b/sorts/bucket_sort.py index bd4281e..aac62e6 100644 --- a/sorts/bucket_sort.py +++ b/sorts/bucket_sort.py @@ -35,10 +35,7 @@ def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): # Initialize buckets bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1 - buckets = [] - for i in range(0, bucketCount): - buckets.append([]) - + buckets = [[] for _ in range(0, bucketCount)] # For putting values in buckets for i in range(0, len(myList)): buckets[math.floor((myList[i] - minValue) / bucketSize)].append(myList[i]) @@ -47,9 +44,7 @@ def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE): sortedArray = [] for i in range(0, len(buckets)): insertion_sort(buckets[i]) - for j in range(0, len(buckets[i])): - sortedArray.append(buckets[i][j]) - + sortedArray.extend(buckets[i][j] for j in range(0, len(buckets[i]))) return sortedArray if __name__ == '__main__': diff --git a/sorts/external-sort.py b/sorts/external-sort.py index 1638e9e..bd25a31 100644 --- a/sorts/external-sort.py +++ b/sorts/external-sort.py @@ -74,10 +74,7 @@ def refresh(self): self.empty.add(i) self.files[i].close() - if len(self.empty) == self.num_buffers: - return False - - return True + return len(self.empty) != self.num_buffers def unshift(self, index): value = self.buffers[index] @@ -98,12 +95,7 @@ def merge(self, filenames, outfilename, buffer_size): outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): - files = {} - - for i in range(len(filenames)): - files[i] = open(filenames[i], 'r', buffer_size) - - return files + return {i: open(filenames[i], 'r', buffer_size) for i in range(len(filenames))} @@ -118,7 +110,7 @@ def sort(self, filename, sort_key=None): merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) - merger.merge(splitter.get_block_filenames(), filename + '.out', buffer_size) + merger.merge(splitter.get_block_filenames(), f'{filename}.out', buffer_size) splitter.cleanup() diff --git a/sorts/pancake_sort.py b/sorts/pancake_sort.py index 26fd40b..9f96733 100644 --- a/sorts/pancake_sort.py +++ b/sorts/pancake_sort.py @@ -5,11 +5,11 @@ def pancakesort(arr): cur = len(arr) while cur > 1: # Find the maximum number in arr - mi = arr.index(max(arr[0:cur])) - # Reverse from 0 to mi - arr = arr[mi::-1] + arr[mi+1:len(arr)] - # Reverse whole list - arr = arr[cur-1::-1] + arr[cur:len(arr)] + mi = arr.index(max(arr[:cur])) + # Reverse from 0 to mi + arr = arr[mi::-1] + arr[mi+1:] + # Reverse whole list + arr = arr[cur-1::-1] + arr[cur:] cur -= 1 return arr diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 136cbc0..0b1cc93 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -30,13 +30,12 @@ def quick_sort(ARRAY): [-45, -5, -2] """ ARRAY_LENGTH = len(ARRAY) - if( ARRAY_LENGTH <= 1): + if ( ARRAY_LENGTH <= 1): return ARRAY - else: - PIVOT = ARRAY[0] - GREATER = [ element for element in ARRAY[1:] if element > PIVOT ] - LESSER = [ element for element in ARRAY[1:] if element <= PIVOT ] - return quick_sort(LESSER) + [PIVOT] + quick_sort(GREATER) + PIVOT = ARRAY[0] + GREATER = [ element for element in ARRAY[1:] if element > PIVOT ] + LESSER = [ element for element in ARRAY[1:] if element <= PIVOT ] + return quick_sort(LESSER) + [PIVOT] + quick_sort(GREATER) if __name__ == '__main__': diff --git a/sorts/radix_sort.py b/sorts/radix_sort.py index e4cee61..547de5f 100644 --- a/sorts/radix_sort.py +++ b/sorts/radix_sort.py @@ -6,21 +6,21 @@ def radixsort(lst): max_digit = max(lst) while placement < max_digit: - # declare and initialize buckets - buckets = [list() for _ in range( RADIX )] + # declare and initialize buckets + buckets = [[] for _ in range( RADIX )] - # split lst between lists - for i in lst: - tmp = int((i / placement) % RADIX) - buckets[tmp].append(i) + # split lst between lists + for i in lst: + tmp = int((i / placement) % RADIX) + buckets[tmp].append(i) - # empty lists into lst array - a = 0 - for b in range( RADIX ): - buck = buckets[b] - for i in buck: - lst[a] = i - a += 1 + # empty lists into lst array + a = 0 + for b in range( RADIX ): + buck = buckets[b] + for i in buck: + lst[a] = i + a += 1 - # move to next - placement *= RADIX + # move to next + placement *= RADIX diff --git a/sorts/timsort.py b/sorts/timsort.py index 80c5cd1..cddf4b6 100644 --- a/sorts/timsort.py +++ b/sorts/timsort.py @@ -1,10 +1,7 @@ from __future__ import print_function def binary_search(lst, item, start, end): if start == end: - if lst[start] > item: - return start - else: - return start + 1 + return start if lst[start] > item else start + 1 if start > end: return start @@ -63,9 +60,7 @@ def timsort(lst): else: new_run.append(lst[i]) - for run in runs: - sorted_runs.append(insertion_sort(run)) - + sorted_runs.extend(insertion_sort(run) for run in runs) for run in sorted_runs: sorted_array = merge(sorted_array, run) diff --git a/strings/levenshtein_distance.py b/strings/levenshtein_distance.py index 274dfd7..9007578 100644 --- a/strings/levenshtein_distance.py +++ b/strings/levenshtein_distance.py @@ -74,5 +74,6 @@ def levenshtein_distance(first_word, second_word): second_word = raw_input('Enter the second word:\n').strip() result = levenshtein_distance(first_word, second_word) - print('Levenshtein distance between {} and {} is {}'.format( - first_word, second_word, result)) + print( + f'Levenshtein distance between {first_word} and {second_word} is {result}' + ) diff --git a/strings/manacher.py b/strings/manacher.py index 9a44b19..faf5c99 100644 --- a/strings/manacher.py +++ b/strings/manacher.py @@ -16,14 +16,8 @@ def palindromic_string( input_string ): 3. return output_string from center - max_length to center + max_length and remove all "|" """ max_length = 0 - - # if input_string is "aba" than new_input_string become "a|b|a" - new_input_string = "" - output_string = "" - - # append each character + "|" in new_string for range(0, length-1) - for i in input_string[:len(input_string)-1] : - new_input_string += i + "|" + + new_input_string = "".join(f"{i}|" for i in input_string[:-1]) #append last character new_input_string += input_string[-1] @@ -38,13 +32,12 @@ def palindromic_string( input_string ): if max_length < length : max_length = length start = i - - #create that string - for i in new_input_string[start-max_length:start+max_length+1] : - if i != "|": - output_string += i - - return output_string + + return "".join( + i + for i in new_input_string[start - max_length : start + max_length + 1] + if i != "|" + ) if __name__ == '__main__': diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index de7f9f7..24c5397 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -52,20 +52,16 @@ def compute_transform_tables(X, Y, cC, cR, cD, cI): def assemble_transformation(ops, i, j): if i == 0 and j == 0: seq = [] - return seq else: - if ops[i][j][0] == 'C' or ops[i][j][0] == 'R': + if ops[i][j][0] in ['C', 'R']: seq = assemble_transformation(ops, i-1, j-1) - seq.append(ops[i][j]) - return seq elif ops[i][j][0] == 'D': seq = assemble_transformation(ops, i-1, j) - seq.append(ops[i][j]) - return seq else: seq = assemble_transformation(ops, i, j-1) - seq.append(ops[i][j]) - return seq + + seq.append(ops[i][j]) + return seq if __name__ == '__main__': _, operations = compute_transform_tables('Python', 'Algorithms', -1, 1, 2, 2) @@ -77,7 +73,7 @@ def assemble_transformation(ops, i, j): string = list('Python') i = 0 cost = 0 - + with open('min_cost.txt', 'w') as file: for op in sequence: print(''.join(string)) @@ -85,37 +81,31 @@ def assemble_transformation(ops, i, j): if op[0] == 'C': file.write('%-16s' % 'Copy %c' % op[1]) file.write('\t\t\t' + ''.join(string)) - file.write('\r\n') - cost -= 1 elif op[0] == 'R': string[i] = op[2] file.write('%-16s' % ('Replace %c' % op[1] + ' with ' + str(op[2]))) file.write('\t\t' + ''.join(string)) - file.write('\r\n') - cost += 1 elif op[0] == 'D': string.pop(i) file.write('%-16s' % 'Delete %c' % op[1]) file.write('\t\t\t' + ''.join(string)) - file.write('\r\n') - cost += 2 else: string.insert(i, op[1]) file.write('%-16s' % 'Insert %c' % op[1]) file.write('\t\t\t' + ''.join(string)) - file.write('\r\n') - cost += 2 + file.write('\r\n') + i += 1 print(''.join(string)) print('Cost: ', cost) - + file.write('\r\nMinimum cost: ' + str(cost)) diff --git a/strings/naiveStringSearch.py b/strings/naiveStringSearch.py index 04c0d81..9732994 100644 --- a/strings/naiveStringSearch.py +++ b/strings/naiveStringSearch.py @@ -12,11 +12,7 @@ def naivePatternSearch(mainString,pattern): strLen=len(mainString) position=[] for i in range(strLen-patLen+1): - match_found=True - for j in range(patLen): - if mainString[i+j]!=pattern[j]: - match_found=False - break + match_found = all(mainString[i+j] == pattern[j] for j in range(patLen)) if match_found: position.append(i) return position diff --git a/traversals/binary_tree_traversals.py b/traversals/binary_tree_traversals.py index 3936645..44ee0d6 100644 --- a/traversals/binary_tree_traversals.py +++ b/traversals/binary_tree_traversals.py @@ -30,7 +30,7 @@ def build_tree(): q.put(tree_node) while not q.empty(): node_found = q.get() - print("Enter the left node of %s: " % node_found.data, end="") + print(f"Enter the left node of {node_found.data}: ", end="") check = raw_input().strip().lower() if check == 'n': return tree_node @@ -38,7 +38,7 @@ def build_tree(): left_node = TreeNode(left_data) node_found.left = left_node q.put(left_node) - print("Enter the right node of %s: " % node_found.data, end="") + print(f"Enter the right node of {node_found.data}: ", end="") check = raw_input().strip().lower() if check == 'n': return tree_node