diff --git a/.gitignore b/.gitignore index b840d4ed0490..574cdf312836 100644 --- a/.gitignore +++ b/.gitignore @@ -26,7 +26,7 @@ wheels/ MANIFEST # PyInstaller -# Usually these files are written by a python script from a template +# Usually these files are written by a Python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec diff --git a/DIRECTORY.md b/DIRECTORY.md index 91a5ab7f6a99..48c1dde9ab67 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -263,7 +263,7 @@ * [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py) ## Maths - * [3N+1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n+1.py) + * [3N+1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py) * [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py) * [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py) * [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py) diff --git a/backtracking/n_queens.py b/backtracking/n_queens.py index c0db41496aee..58d9c4279a35 100644 --- a/backtracking/n_queens.py +++ b/backtracking/n_queens.py @@ -42,7 +42,7 @@ def solve(board, row): """ It creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next - poosible solution branch. + possible solution branch. """ if row >= len(board): """ @@ -56,7 +56,7 @@ def solve(board, row): return for i in range(len(board)): """ - For every row it iterates through each column to check if it is feesible to place a + For every row it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful the board is reinitialized for the next possible combination. diff --git a/ciphers/hill_cipher.py b/ciphers/hill_cipher.py index ffc1d9793bf2..47910e4ebdaa 100644 --- a/ciphers/hill_cipher.py +++ b/ciphers/hill_cipher.py @@ -65,11 +65,11 @@ def __init__(self, encrypt_key): encrypt_key is an NxN numpy matrix """ self.encrypt_key = self.modulus(encrypt_key) # mod36 calc's on the encrypt key - self.checkDeterminant() # validate the determinant of the encryption key + self.check_determinant() # validate the determinant of the encryption key self.decrypt_key = None self.break_key = encrypt_key.shape[0] - def checkDeterminant(self): + def check_determinant(self): det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: @@ -83,7 +83,7 @@ def checkDeterminant(self): ) ) - def processText(self, text): + def process_text(self, text): text = list(text.upper()) text = [char for char in text if char in self.key_string] @@ -94,7 +94,7 @@ def processText(self, text): return "".join(text) def encrypt(self, text): - text = self.processText(text.upper()) + text = self.process_text(text.upper()) encrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): @@ -109,7 +109,7 @@ def encrypt(self, text): return encrypted - def makeDecryptKey(self): + def make_decrypt_key(self): det = round(numpy.linalg.det(self.encrypt_key)) if det < 0: @@ -129,8 +129,8 @@ def makeDecryptKey(self): return self.toInt(self.modulus(inv_key)) def decrypt(self, text): - self.decrypt_key = self.makeDecryptKey() - text = self.processText(text.upper()) + self.decrypt_key = self.make_decrypt_key() + text = self.process_text(text.upper()) decrypted = "" for i in range(0, len(text) - self.break_key + 1, self.break_key): diff --git a/ciphers/onepad_cipher.py b/ciphers/onepad_cipher.py index 5a410bfa638a..fe07908afff5 100644 --- a/ciphers/onepad_cipher.py +++ b/ciphers/onepad_cipher.py @@ -3,7 +3,7 @@ class Onepad: def encrypt(self, text): - """Function to encrypt text using psedo-random numbers""" + """Function to encrypt text using pseudo-random numbers""" plain = [ord(i) for i in text] key = [] cipher = [] @@ -15,7 +15,7 @@ def encrypt(self, text): return cipher, key def decrypt(self, cipher, key): - """Function to decrypt text using psedo-random numbers.""" + """Function to decrypt text using pseudo-random numbers.""" plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) diff --git a/data_structures/binary_tree/binary_search_tree.py b/data_structures/binary_tree/binary_search_tree.py index 86dcd6489bd5..40546875216b 100644 --- a/data_structures/binary_tree/binary_search_tree.py +++ b/data_structures/binary_tree/binary_search_tree.py @@ -28,16 +28,16 @@ def __str__(self): """ return str(self.root) - def __reassign_nodes(self, node, newChildren): - if newChildren is not None: # reset its kids - newChildren.parent = node.parent + def __reassign_nodes(self, node, new_children): + if new_children is not None: # reset its kids + new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children - node.parent.right = newChildren + node.parent.right = new_children else: - node.parent.left = newChildren + node.parent.left = new_children else: - self.root = newChildren + self.root = new_children def is_right(self, node): return node == node.parent.right @@ -117,39 +117,39 @@ def remove(self, value): elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: - tmpNode = self.get_max( + tmp_node = self.get_max( node.left - ) # Gets the max value of the left branch - self.remove(tmpNode.value) + ) # Gets the max value of the left branch + self.remove(tmp_node.value) node.value = ( - tmpNode.value - ) # Assigns the value to the node to delete and keesp tree structure + tmp_node.value + ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node): if node is not None: - yield node # Preorder Traversal + yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) - def traversal_tree(self, traversalFunction=None): + def traversal_tree(self, traversal_function=None): """ This function traversal the tree. You can pass a function to traversal the tree as needed by client code """ - if traversalFunction is None: + if traversal_function is None: return self.preorder_traverse(self.root) else: - return traversalFunction(self.root) + return traversal_function(self.root) def postorder(curr_node): """ postOrder (left, right, self) """ - nodeList = list() + node_list = list() if curr_node is not None: - nodeList = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] - return nodeList + node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] + return node_list def binary_search_tree(): diff --git a/data_structures/binary_tree/number_of_possible_binary_trees.py b/data_structures/binary_tree/number_of_possible_binary_trees.py index d053ba31171f..1ad8f2ed4287 100644 --- a/data_structures/binary_tree/number_of_possible_binary_trees.py +++ b/data_structures/binary_tree/number_of_possible_binary_trees.py @@ -82,7 +82,7 @@ def binary_tree_count(node_count: int) -> int: """ Return the number of possible of binary trees. :param n: number of nodes - :return: Number of possilble binary trees + :return: Number of possible binary trees >>> binary_tree_count(5) 5040 diff --git a/data_structures/linked_list/deque_doubly.py b/data_structures/linked_list/deque_doubly.py index 0898db679802..b2e73a8f789b 100644 --- a/data_structures/linked_list/deque_doubly.py +++ b/data_structures/linked_list/deque_doubly.py @@ -21,7 +21,7 @@ def __init__(self, link_p, element, link_n): def has_next_and_prev(self): return " Prev -> {0}, Next -> {1}".format( - self._prev != None, self._next != None + self._prev is not None, self._next is not None ) def __init__(self): diff --git a/data_structures/linked_list/doubly_linked_list.py b/data_structures/linked_list/doubly_linked_list.py index 27b04ed39ad2..f8f652be6d32 100644 --- a/data_structures/linked_list/doubly_linked_list.py +++ b/data_structures/linked_list/doubly_linked_list.py @@ -62,7 +62,7 @@ def isEmpty(self): # Will return True if the list is empty def display(self): # Prints contents of the list current = self.head - while current != None: + while current is not None: current.displayLink() current = current.next print() diff --git a/data_structures/queue/queue_on_list.py b/data_structures/queue/queue_on_list.py index bb44e08ad6c5..4d69461af66a 100644 --- a/data_structures/queue/queue_on_list.py +++ b/data_structures/queue/queue_on_list.py @@ -1,4 +1,4 @@ -"""Queue represented by a python list""" +"""Queue represented by a Python list""" class Queue: diff --git a/digital_image_processing/change_contrast.py b/digital_image_processing/change_contrast.py index 76f1a3e1fcd8..c7da52298ae2 100644 --- a/digital_image_processing/change_contrast.py +++ b/digital_image_processing/change_contrast.py @@ -2,7 +2,7 @@ Changing contrast with PIL This algorithm is used in -https://noivce.pythonanywhere.com/ python web app. +https://noivce.pythonanywhere.com/ Python web app. python/black: True flake8 : True diff --git a/divide_and_conquer/convex_hull.py b/divide_and_conquer/convex_hull.py index 76184524e266..11b16975c8b4 100644 --- a/divide_and_conquer/convex_hull.py +++ b/divide_and_conquer/convex_hull.py @@ -344,19 +344,19 @@ def convex_hull_recursive(points): right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} - upperhull = [] - lowerhull = [] + upper_hull = [] + lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: - upperhull.append(points[i]) + upper_hull.append(points[i]) elif det < 0: - lowerhull.append(points[i]) + lower_hull.append(points[i]) - _construct_hull(upperhull, left_most_point, right_most_point, convex_set) - _construct_hull(lowerhull, right_most_point, left_most_point, convex_set) + _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) + _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) diff --git a/dynamic_programming/bitmask.py b/dynamic_programming/bitmask.py index 1841f1747557..625a0809c4b9 100644 --- a/dynamic_programming/bitmask.py +++ b/dynamic_programming/bitmask.py @@ -1,6 +1,6 @@ """ -This is a python implementation for questions involving task assignments between people. +This is a Python implementation for questions involving task assignments between people. Here Bitmasking and DP are used for solving this. Question :- @@ -25,41 +25,41 @@ def __init__(self, task_performed, total): 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 << len(task_performed)) - 1 + # final_mask is used to check if all persons are included by setting all bits to 1 + self.final_mask = (1 << len(task_performed)) - 1 - def CountWaysUtil(self, mask, taskno): + def CountWaysUtil(self, mask, task_no): # if mask == self.finalmask all persons are distributed tasks, return 1 - if mask == self.finalmask: + if mask == self.final_mask: return 1 # if not everyone gets the task and no more tasks are available, return 0 - if taskno > self.total_tasks: + if task_no > self.total_tasks: return 0 # if case already considered - if self.dp[mask][taskno] != -1: - return self.dp[mask][taskno] + if self.dp[mask][task_no] != -1: + return self.dp[mask][task_no] # Number of ways when we don't this task in the arrangement - total_ways_util = self.CountWaysUtil(mask, taskno + 1) + total_ways_util = self.CountWaysUtil(mask, task_no + 1) # now assign the tasks one by one to all possible persons and recursively assign for the remaining tasks. - if taskno in self.task: - for p in self.task[taskno]: + if task_no in self.task: + for p in self.task[task_no]: # if p is already given a task if mask & (1 << p): continue # assign this task to p and change the mask value. And recursively assign tasks with the new mask value. - total_ways_util += self.CountWaysUtil(mask | (1 << p), taskno + 1) + total_ways_util += self.CountWaysUtil(mask | (1 << p), task_no + 1) # save the value. - self.dp[mask][taskno] = total_ways_util + self.dp[mask][task_no] = total_ways_util - return self.dp[mask][taskno] + return self.dp[mask][task_no] def countNoOfWays(self, task_performed): diff --git a/dynamic_programming/fibonacci.py b/dynamic_programming/fibonacci.py index 923560b54d30..45319269f5d4 100644 --- a/dynamic_programming/fibonacci.py +++ b/dynamic_programming/fibonacci.py @@ -28,7 +28,7 @@ def get(self, sequence_no=None): [0, 1, 1, 2, 3, 5] [] """ - if sequence_no != None: + if sequence_no is not None: if sequence_no < len(self.fib_array): return print(self.fib_array[: sequence_no + 1]) else: diff --git a/fuzzy_logic/fuzzy_operations.py b/fuzzy_logic/fuzzy_operations.py index cb870e8d9e3b..34dd9c029be7 100644 --- a/fuzzy_logic/fuzzy_operations.py +++ b/fuzzy_logic/fuzzy_operations.py @@ -11,7 +11,7 @@ if __name__ == "__main__": - # Create universe of discourse in python using linspace () + # Create universe of discourse in Python using linspace () X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function (trapmf(), gbellmf(),gaussmf(), etc). diff --git a/graphs/bellman_ford.py b/graphs/bellman_ford.py index 6b5e8b735c43..807e0b0fcdb9 100644 --- a/graphs/bellman_ford.py +++ b/graphs/bellman_ford.py @@ -8,7 +8,7 @@ def printDist(dist, V): def BellmanFord(graph: List[Dict[str, int]], V: int, E: int, src: int) -> int: - r""" + """ Returns shortest paths from a vertex src to all other vertices. """ diff --git a/graphs/directed_and_undirected_(weighted)_graph.py b/graphs/directed_and_undirected_(weighted)_graph.py index 15e2ce663594..26c87cd8f4b2 100644 --- a/graphs/directed_and_undirected_(weighted)_graph.py +++ b/graphs/directed_and_undirected_(weighted)_graph.py @@ -3,7 +3,7 @@ import math as math import time -# the dfault weight is 1 if not assigned but all the implementation is weighted +# the default weight is 1 if not assigned but all the implementation is weighted class DirectedGraph: diff --git a/graphs/minimum_spanning_tree_prims.py b/graphs/minimum_spanning_tree_prims.py index 216d6a3f56de..6255b6af64ad 100644 --- a/graphs/minimum_spanning_tree_prims.py +++ b/graphs/minimum_spanning_tree_prims.py @@ -6,13 +6,13 @@ def PrimsAlgorithm(l): nodePosition = [] - def getPosition(vertex): + def get_position(vertex): return nodePosition[vertex] - def setPosition(vertex, pos): + def set_position(vertex, pos): nodePosition[vertex] = pos - def topToBottom(heap, start, size, positions): + def top_to_bottom(heap, start, size, positions): if start > size // 2 - 1: return else: @@ -28,14 +28,14 @@ def topToBottom(heap, start, size, positions): 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) + temp = get_position(positions[m]) + set_position(positions[m], get_position(positions[start])) + set_position(positions[start], temp) - topToBottom(heap, m, size, positions) + top_to_bottom(heap, m, size, positions) # Update function if value of any node in min-heap decreases - def bottomToTop(val, index, heap, position): + def bottom_to_top(val, index, heap, position): temp = position[index] while index != 0: @@ -47,27 +47,27 @@ def bottomToTop(val, index, heap, position): if val < heap[parent]: heap[index] = heap[parent] position[index] = position[parent] - setPosition(position[parent], index) + set_position(position[parent], index) else: heap[index] = val position[index] = temp - setPosition(temp, index) + set_position(temp, index) break index = parent else: heap[0] = val position[0] = temp - setPosition(temp, 0) + set_position(temp, 0) def heapify(heap, positions): start = len(heap) // 2 - 1 for i in range(start, -1, -1): - topToBottom(heap, i, len(heap), positions) + top_to_bottom(heap, i, len(heap), positions) def deleteMinimum(heap, positions): temp = positions[0] heap[0] = sys.maxsize - topToBottom(heap, 0, len(heap), positions) + top_to_bottom(heap, 0, len(heap), positions) return temp visited = [0 for i in range(len(l))] @@ -96,9 +96,9 @@ def deleteMinimum(heap, positions): TreeEdges.append((Nbr_TV[vertex], vertex)) visited[vertex] = 1 for v in l[vertex]: - if visited[v[0]] == 0 and v[1] < Distance_TV[getPosition(v[0])]: - Distance_TV[getPosition(v[0])] = v[1] - bottomToTop(v[1], getPosition(v[0]), Distance_TV, Positions) + if visited[v[0]] == 0 and v[1] < Distance_TV[get_position(v[0])]: + Distance_TV[get_position(v[0])] = v[1] + bottom_to_top(v[1], get_position(v[0]), Distance_TV, Positions) Nbr_TV[v[0]] = vertex return TreeEdges diff --git a/graphs/multi_heuristic_astar.py b/graphs/multi_heuristic_astar.py index 56cfc727d338..386aab695bb0 100644 --- a/graphs/multi_heuristic_astar.py +++ b/graphs/multi_heuristic_astar.py @@ -52,25 +52,25 @@ def get(self): return (priority, item) -def consistent_hueristic(P, goal): +def consistent_heuristic(P, goal): # euclidean distance a = np.array(P) b = np.array(goal) return np.linalg.norm(a - b) -def hueristic_2(P, goal): +def heuristic_2(P, goal): # integer division by time variable - return consistent_hueristic(P, goal) // t + return consistent_heuristic(P, goal) // t -def hueristic_1(P, goal): +def heuristic_1(P, goal): # manhattan distance 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) + ans = g_function[start] + W1 * heuristics[i](start, goal) return ans @@ -134,7 +134,7 @@ def expand_state( open_list, back_pointer, ): - for itera in range(n_hueristic): + for itera in range(n_heuristic): open_list[itera].remove_element(s) # print("s", s) # print("j", j) @@ -158,30 +158,24 @@ def expand_state( if neighbours not in close_list_anchor: open_list[0].put(neighbours, key(neighbours, 0, goal, g_function)) if neighbours not in close_list_inad: - for var in range(1, n_hueristic): + for var in range(1, n_heuristic): if key(neighbours, var, goal, g_function) <= W2 * key( neighbours, 0, goal, g_function ): - # print("why not plssssssssss") open_list[j].put( neighbours, key(neighbours, var, goal, g_function) ) - # 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)) @@ -196,7 +190,7 @@ def make_common_ground(): return some_list -hueristics = {0: consistent_hueristic, 1: hueristic_1, 2: hueristic_2} +heuristics = {0: consistent_heuristic, 1: heuristic_1, 2: heuristic_2} blocks_blk = [ (0, 1), @@ -229,7 +223,7 @@ def make_common_ground(): W1 = 1 W2 = 1 n = 20 -n_hueristic = 3 # one consistent and two other inconsistent +n_heuristic = 3 # one consistent and two other inconsistent # start and end destination start = (0, 0) @@ -238,26 +232,24 @@ def make_common_ground(): t = 1 -def multi_a_star(start, goal, n_hueristic): +def multi_a_star(start, goal, n_heuristic): g_function = {start: 0, goal: float("inf")} back_pointer = {start: -1, goal: -1} open_list = [] visited = set() - for i in range(n_hueristic): + for i in range(n_heuristic): 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) + for i in range(1, n_heuristic): # 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) @@ -276,12 +268,10 @@ def multi_a_star(start, goal, n_hueristic): ) 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( @@ -319,4 +309,4 @@ def multi_a_star(start, goal, n_hueristic): if __name__ == "__main__": - multi_a_star(start, goal, n_hueristic) + multi_a_star(start, goal, n_heuristic) diff --git a/hashes/hamming_code.py b/hashes/hamming_code.py index 756ba7c6670f..c1ed7fe1d727 100644 --- a/hashes/hamming_code.py +++ b/hashes/hamming_code.py @@ -121,7 +121,7 @@ def emitterConverter(sizePar, data): # counter to control the loop reading contLoop = 0 for x in dataOrd: - if x != None: + if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: @@ -224,7 +224,7 @@ def receptorConverter(sizePar, data): # Counter to control loop reading contLoop = 0 for x in dataOrd: - if x != None: + if x is not None: try: aux = (binPos[contLoop])[-1 * (bp)] except IndexError: diff --git a/machine_learning/linear_regression.py b/machine_learning/linear_regression.py index b666feddccc7..29bb7c48589e 100644 --- a/machine_learning/linear_regression.py +++ b/machine_learning/linear_regression.py @@ -1,10 +1,10 @@ """ Linear regression is the most basic type of regression commonly used for -predictive analysis. The idea is pretty simple, we have a dataset and we have -a feature's associated with it. The Features should be choose very cautiously -as they determine, how much our model will be able to make future predictions. -We try to set these Feature weights, over many iterations, so that they best -fits our dataset. In this particular code, i had used a CSGO dataset (ADR vs +predictive analysis. The idea is pretty simple: we have a dataset and we have +features associated with it. Features should be chosen very cautiously +as they determine how much our model will be able to make future predictions. +We try to set the weight of these features, over many iterations, so that they best +fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import requests diff --git a/maths/3n+1.py b/maths/3n_plus_1.py similarity index 97% rename from maths/3n+1.py rename to maths/3n_plus_1.py index 64ff34fd2039..d3684561827f 100644 --- a/maths/3n+1.py +++ b/maths/3n_plus_1.py @@ -3,7 +3,7 @@ def n31(a: int) -> Tuple[List[int], int]: """ - Returns the Collatz sequence and its length of any postiver integer. + Returns the Collatz sequence and its length of any positive integer. >>> n31(4) ([4, 2, 1], 3) """ diff --git a/maths/average_mode.py b/maths/average_mode.py index c1a4b3521448..d472dc04d4bf 100644 --- a/maths/average_mode.py +++ b/maths/average_mode.py @@ -14,7 +14,7 @@ def mode(input_list): # Defining function "mode." >>> mode(input_list) == statistics.mode(input_list) True """ - # Copying inputlist to check with the index number later. + # Copying input_list to check with the index number later. check_list = input_list.copy() result = list() # Empty list to store the counts of elements in input_list for x in input_list: diff --git a/maths/basic_maths.py b/maths/basic_maths.py index 5dbfd250d308..07ee3b3df296 100644 --- a/maths/basic_maths.py +++ b/maths/basic_maths.py @@ -63,7 +63,7 @@ def sum_of_divisors(n: int) -> int: def euler_phi(n: int) -> int: - """Calculte Euler's Phi Function. + """Calculate Euler's Phi Function. >>> euler_phi(100) 40 """ diff --git a/maths/explicit_euler.py b/maths/explicit_euler.py index 8a43d71fb432..7c780198602b 100644 --- a/maths/explicit_euler.py +++ b/maths/explicit_euler.py @@ -1,7 +1,7 @@ import numpy as np -def explicit_euler(ode_func, y0, x0, stepsize, x_end): +def explicit_euler(ode_func, y0, x0, step_size, x_end): """ Calculate numeric solution at each step to an ODE using Euler's Method @@ -22,14 +22,14 @@ def explicit_euler(ode_func, y0, x0, stepsize, x_end): >>> y[-1] 144.77277243257308 """ - N = int(np.ceil((x_end - x0) / stepsize)) + N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): - y[k + 1] = y[k] + stepsize * ode_func(x, y[k]) - x += stepsize + y[k + 1] = y[k] + step_size * ode_func(x, y[k]) + x += step_size return y diff --git a/maths/factorial_iterative.py b/maths/factorial_iterative.py index 249408cb5b4e..64314790c11c 100644 --- a/maths/factorial_iterative.py +++ b/maths/factorial_iterative.py @@ -26,5 +26,5 @@ def factorial(n: int) -> int: if __name__ == "__main__": - n = int(input("Enter a positivve integer: ").strip() or 0) + n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}") diff --git a/other/anagrams.py b/other/anagrams.py index 6e6806e92a0f..471413194498 100644 --- a/other/anagrams.py +++ b/other/anagrams.py @@ -16,8 +16,8 @@ def signature(word): word_bysig[signature(word)].append(word) -def anagram(myword): - return word_bysig[signature(myword)] +def anagram(my_word): + return word_bysig[signature(my_word)] print("finding anagrams...") diff --git a/other/autocomplete_using_trie.py b/other/autocomplete_using_trie.py index eb906f8efa9a..8aa0dc223680 100644 --- a/other/autocomplete_using_trie.py +++ b/other/autocomplete_using_trie.py @@ -26,10 +26,10 @@ def _elements(self, d): result = [] for c, v in d.items(): if c == END: - subresult = [" "] + sub_result = [" "] else: - subresult = [c + s for s in self._elements(v)] - result.extend(subresult) + sub_result = [c + s for s in self._elements(v)] + result.extend(sub_result) return tuple(result) diff --git a/other/fischer_yates_shuffle.py b/other/fischer_yates_shuffle.py index 4217cb0bef67..99121ba632c7 100644 --- a/other/fischer_yates_shuffle.py +++ b/other/fischer_yates_shuffle.py @@ -7,12 +7,12 @@ import random -def FYshuffle(LIST): - for i 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] - return LIST +def FYshuffle(list): + for i 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] + return list if __name__ == "__main__": diff --git a/other/magicdiamondpattern.py b/other/magicdiamondpattern.py index 6de5046c9f18..4ca698d80c28 100644 --- a/other/magicdiamondpattern.py +++ b/other/magicdiamondpattern.py @@ -1,4 +1,4 @@ -# Python program for generating diamond pattern in python 3.7+ +# Python program for generating diamond pattern in Python 3.7+ # Function to print upper half of diamond (pyramid) def floyd(n): diff --git a/other/primelib.py b/other/primelib.py index 1b99819ce62a..a6d1d7dfb324 100644 --- a/other/primelib.py +++ b/other/primelib.py @@ -3,7 +3,7 @@ @author: Christian Bender -This python library contains some useful functions to deal with +This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: diff --git a/project_euler/problem_04/sol2.py b/project_euler/problem_04/sol2.py index ecc503912c34..0f185f1216ab 100644 --- a/project_euler/problem_04/sol2.py +++ b/project_euler/problem_04/sol2.py @@ -20,7 +20,7 @@ def solution(n): 39893 """ answer = 0 - for i in range(999, 99, -1): # 3 digit nimbers range from 999 down to 100 + for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100 for j in range(999, 99, -1): t = str(i * j) if t == t[::-1] and i * j < n: diff --git a/project_euler/problem_07/sol1.py b/project_euler/problem_07/sol1.py index f6b2584d9cdc..373915f886e1 100644 --- a/project_euler/problem_07/sol1.py +++ b/project_euler/problem_07/sol1.py @@ -8,7 +8,7 @@ from math import sqrt -def isprime(n): +def is_prime(n): if n == 2: return True elif n % 2 == 0: @@ -41,11 +41,11 @@ def solution(n): j = 1 while i != n and j < 3: j += 1 - if isprime(j): + if is_prime(j): i += 1 while i != n: j += 2 - if isprime(j): + if is_prime(j): i += 1 return j diff --git a/project_euler/problem_551/sol1.py b/project_euler/problem_551/sol1.py index 4775800693bc..873e520cc9b4 100644 --- a/project_euler/problem_551/sol1.py +++ b/project_euler/problem_551/sol1.py @@ -52,10 +52,10 @@ def next_term(a_i, k, i, n): sub_memo = memo.get(ds_b) - if sub_memo != None: + if sub_memo is not None: jumps = sub_memo.get(c) - if jumps != None and len(jumps) > 0: + if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): diff --git a/scripts/build_directory_md.py b/scripts/build_directory_md.py index 1043e6ccb696..9e26ee81a323 100755 --- a/scripts/build_directory_md.py +++ b/scripts/build_directory_md.py @@ -6,14 +6,14 @@ URL_BASE = "https://github.com/TheAlgorithms/Python/blob/master" -def good_filepaths(top_dir: str = ".") -> Iterator[str]: - for dirpath, dirnames, filenames in os.walk(top_dir): - dirnames[:] = [d for d in dirnames if d != "scripts" and d[0] not in "._"] +def good_file_paths(top_dir: str = ".") -> Iterator[str]: + for dir_path, dir_names, filenames in os.walk(top_dir): + dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): - yield os.path.join(dirpath, filename).lstrip("./") + yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(i): @@ -31,7 +31,7 @@ def print_path(old_path: str, new_path: str) -> str: def print_directory_md(top_dir: str = ".") -> None: old_path = "" - for filepath in sorted(good_filepaths()): + for filepath in sorted(good_file_paths()): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) diff --git a/scripts/validate_filenames.py b/scripts/validate_filenames.py index 51dd6a40cb41..f22fda4149f3 100755 --- a/scripts/validate_filenames.py +++ b/scripts/validate_filenames.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 import os -from build_directory_md import good_filepaths +from build_directory_md import good_file_paths -filepaths = list(good_filepaths()) -assert filepaths, "good_filepaths() failed!" +filepaths = list(good_file_paths()) +assert filepaths, "good_file_paths() failed!" upper_files = [file for file in filepaths if file != file.lower()] diff --git a/searches/binary_search.py b/searches/binary_search.py index fe22e423a7d4..8edf63136f9a 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of binary search algorithms +This is pure Python implementation of binary search algorithms For doctests run following command: python -m doctest -v binary_search.py diff --git a/searches/interpolation_search.py b/searches/interpolation_search.py index 419ec52c0f4e..f4fa8e1203df 100644 --- a/searches/interpolation_search.py +++ b/searches/interpolation_search.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of interpolation search algorithm +This is pure Python implementation of interpolation search algorithm """ diff --git a/searches/linear_search.py b/searches/linear_search.py index b6f52ca4857f..76683dc6a6a8 100644 --- a/searches/linear_search.py +++ b/searches/linear_search.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of linear search algorithm +This is pure Python implementation of linear search algorithm For doctests run following command: python -m doctest -v linear_search.py diff --git a/searches/sentinel_linear_search.py b/searches/sentinel_linear_search.py index 5650151b1d2f..69c1cf9f351a 100644 --- a/searches/sentinel_linear_search.py +++ b/searches/sentinel_linear_search.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of sentinel linear search algorithm +This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py diff --git a/searches/simulated_annealing.py b/searches/simulated_annealing.py index d3542b00af45..c24adc1ddb41 100644 --- a/searches/simulated_annealing.py +++ b/searches/simulated_annealing.py @@ -66,15 +66,15 @@ def simulated_annealing( if change > 0: # improves the solution next_state = picked_neighbor else: - probabililty = (math.e) ** ( + probability = (math.e) ** ( change / current_temp ) # probability generation function - if random.random() < probabililty: # random number within probability + if random.random() < probability: # random number within probability next_state = picked_neighbor current_temp = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: - # temperature below threshold, or could not find a suitaable neighbor + # temperature below threshold, or could not find a suitable neighbor search_end = True else: current_state = next_state diff --git a/searches/tabu_search.py b/searches/tabu_search.py index 2847dca7acd7..9ddc5e8dee7f 100644 --- a/searches/tabu_search.py +++ b/searches/tabu_search.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances +This is pure Python implementation of Tabu search algorithm for a Travelling Salesman Problem, that the distances between the cities are symmetric (the distance between city 'a' and city 'b' is the same between city 'b' and city 'a'). The TSP can be represented into a graph. The cities are represented by nodes and the distance between them is represented by the weight of the ark between the nodes. diff --git a/sorts/bitonic_sort.py b/sorts/bitonic_sort.py index 131f97291fbb..ce80c6028729 100644 --- a/sorts/bitonic_sort.py +++ b/sorts/bitonic_sort.py @@ -14,36 +14,36 @@ def compAndSwap(a, i, j, dire): # if dir = 1, and in descending order otherwise (means dir=0). # The sequence to be sorted starts at index position low, # the parameter cnt is the number of elements to be sorted. -def bitonicMerge(a, low, cnt, dire): +def bitonic_merge(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) for i in range(low, low + k): compAndSwap(a, i, i + k, dire) - bitonicMerge(a, low, k, dire) - bitonicMerge(a, low + k, k, dire) + bitonic_merge(a, low, k, dire) + bitonic_merge(a, low + k, k, dire) # This function first produces a bitonic sequence by recursively # sorting its two halves in opposite sorting orders, and then -# calls bitonicMerge to make them in the same order -def bitonicSort(a, low, cnt, dire): +# calls bitonic_merge to make them in the same order +def bitonic_sort(a, low, cnt, dire): if cnt > 1: k = int(cnt / 2) - bitonicSort(a, low, k, 1) - bitonicSort(a, low + k, k, 0) - bitonicMerge(a, low, cnt, dire) + bitonic_sort(a, low, k, 1) + bitonic_sort(a, low + k, k, 0) + bitonic_merge(a, low, cnt, dire) - # Caller of bitonicSort for sorting the entire array of length N + # Caller of bitonic_sort for sorting the entire array of length N # in ASCENDING order def sort(a, N, up): - bitonicSort(a, 0, N, up) + bitonic_sort(a, 0, N, up) if __name__ == "__main__": - # Driver code to test above + a = [] n = int(input().strip()) diff --git a/sorts/bogo_sort.py b/sorts/bogo_sort.py index 0afa444e5b8e..b72f2089f3d2 100644 --- a/sorts/bogo_sort.py +++ b/sorts/bogo_sort.py @@ -1,5 +1,10 @@ """ -This is a pure python implementation of the bogosort algorithm +This is a pure Python implementation of the bogosort algorithm, +also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort. +Bogosort generates random permutations until it guesses the correct one. + +More info on: https://en.wikipedia.org/wiki/Bogosort + For doctests run following command: python -m doctest -v bogo_sort.py or @@ -25,7 +30,7 @@ def bogo_sort(collection): [-45, -5, -2] """ - def isSorted(collection): + def is_sorted(collection): if len(collection) < 2: return True for i in range(len(collection) - 1): @@ -33,7 +38,7 @@ def isSorted(collection): return False return True - while not isSorted(collection): + while not is_sorted(collection): random.shuffle(collection) return collection diff --git a/sorts/comb_sort.py b/sorts/comb_sort.py index 3c4c57483e3f..c36bb8e63748 100644 --- a/sorts/comb_sort.py +++ b/sorts/comb_sort.py @@ -1,8 +1,13 @@ """ +This is pure Python implementation of comb sort algorithm. Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980. -Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort. +It was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort algorithm. +In bubble sort, distance (or gap) between two compared elements is always one. +Comb sort improvement is that gap can be much more than 1, in order to prevent slowing down by small values +at the end of a list. + +More info on: https://en.wikipedia.org/wiki/Comb_sort -This is pure python implementation of comb sort algorithm For doctests run following command: python -m doctest -v comb_sort.py or @@ -13,42 +18,44 @@ """ -def comb_sort(data): +def comb_sort(data: list) -> list: """Pure implementation of comb sort algorithm in Python - :param collection: some mutable ordered collection with heterogeneous - comparable items inside - :return: the same collection ordered by ascending + :param data: mutable collection with comparable items + :return: the same collection in ascending order Examples: >>> comb_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> comb_sort([]) [] - >>> comb_sort([-2, -5, -45]) - [-45, -5, -2] + >>> comb_sort([99, 45, -7, 8, 2, 0, -15, 3]) + [-15, -7, 0, 2, 3, 8, 45, 99] """ shrink_factor = 1.3 gap = len(data) - swapped = True - i = 0 + completed = False - while gap > 1 or swapped: - # Update the gap value for a next comb - gap = int(float(gap) / shrink_factor) + while not completed: - swapped = False - i = 0 + # Update the gap value for a next comb + gap = int(gap / shrink_factor) + if gap <= 1: + completed = True - while gap + i < len(data): - if data[i] > data[i + gap]: + index = 0 + while index + gap < len(data): + if data[index] > data[index + gap]: # Swap values - data[i], data[i + gap] = data[i + gap], data[i] - swapped = True - i += 1 + data[index], data[index + gap] = data[index + gap], data[index] + completed = False + index += 1 return data if __name__ == "__main__": + import doctest + doctest.testmod() + user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(comb_sort(unsorted)) diff --git a/sorts/counting_sort.py b/sorts/counting_sort.py index b672d4af47cb..892ec5d5f344 100644 --- a/sorts/counting_sort.py +++ b/sorts/counting_sort.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of counting sort algorithm +This is pure Python implementation of counting sort algorithm For doctests run following command: python -m doctest -v counting_sort.py or diff --git a/sorts/heap_sort.py b/sorts/heap_sort.py index a39ae2b88da2..4dca879bd89c 100644 --- a/sorts/heap_sort.py +++ b/sorts/heap_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the heap sort algorithm. +This is a pure Python implementation of the heap sort algorithm. For doctests run following command: python -m doctest -v heap_sort.py diff --git a/sorts/insertion_sort.py b/sorts/insertion_sort.py index b767018c3d57..ca678381b431 100644 --- a/sorts/insertion_sort.py +++ b/sorts/insertion_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the insertion sort algorithm +This is a pure Python implementation of the insertion sort algorithm For doctests run following command: python -m doctest -v insertion_sort.py diff --git a/sorts/merge_sort.py b/sorts/merge_sort.py index 13f1144d4ad3..e8031a1cb97c 100644 --- a/sorts/merge_sort.py +++ b/sorts/merge_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the merge sort algorithm +This is a pure Python implementation of the merge sort algorithm For doctests run following command: python -m doctest -v merge_sort.py diff --git a/sorts/odd_even_transposition_parallel.py b/sorts/odd_even_transposition_parallel.py index 080c86af5a8c..5de7a016c628 100644 --- a/sorts/odd_even_transposition_parallel.py +++ b/sorts/odd_even_transposition_parallel.py @@ -18,7 +18,7 @@ """ The function run by the processes that sorts the list -position = the position in the list the prcoess represents, used to know which +position = the position in the list the process represents, used to know which neighbor we pass our value to value = the initial value at list[position] LSend, RSend = the pipes we use to send to our left and right neighbors @@ -35,7 +35,7 @@ def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe): # find out we are sorted as it does to sort the list with this algorithm for i in range(0, 10): - if (i + position) % 2 == 0 and RSend != None: + if (i + position) % 2 == 0 and RSend is not None: # send your value to your right neighbor processLock.acquire() RSend[1].send(value) @@ -48,7 +48,7 @@ def oeProcess(position, value, LSend, RSend, LRcv, RRcv, resultPipe): # take the lower value since you are on the left value = min(value, temp) - elif (i + position) % 2 != 0 and LSend != None: + elif (i + position) % 2 != 0 and LSend is not None: # send your value to your left neighbor processLock.acquire() LSend[1].send(value) diff --git a/sorts/pancake_sort.py b/sorts/pancake_sort.py index ee54e57f9e0f..e5d600738435 100644 --- a/sorts/pancake_sort.py +++ b/sorts/pancake_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the pancake sort algorithm +This is a pure Python implementation of the pancake sort algorithm For doctests run following command: python3 -m doctest -v pancake_sort.py or diff --git a/sorts/quick_sort.py b/sorts/quick_sort.py index 29e10206f720..f2a55c58b437 100644 --- a/sorts/quick_sort.py +++ b/sorts/quick_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the quick sort algorithm +This is a pure Python implementation of the quick sort algorithm For doctests run following command: python -m doctest -v quick_sort.py diff --git a/sorts/selection_sort.py b/sorts/selection_sort.py index 6a9c063d3364..f3beb31b7070 100644 --- a/sorts/selection_sort.py +++ b/sorts/selection_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the selection sort algorithm +This is a pure Python implementation of the selection sort algorithm For doctests run following command: python -m doctest -v selection_sort.py diff --git a/sorts/shell_sort.py b/sorts/shell_sort.py index ff9c2785b218..80d95870f95b 100644 --- a/sorts/shell_sort.py +++ b/sorts/shell_sort.py @@ -1,5 +1,5 @@ """ -This is a pure python implementation of the shell sort algorithm +This is a pure Python implementation of the shell sort algorithm For doctests run following command: python -m doctest -v shell_sort.py diff --git a/sorts/unknown_sort.py b/sorts/unknown_sort.py index 087533b4a575..5ecc55e9cf69 100644 --- a/sorts/unknown_sort.py +++ b/sorts/unknown_sort.py @@ -1,7 +1,7 @@ """ Python implementation of a sort algorithm. Best Case Scenario : O(n) -Worst Case Scenario : O(n^2) because native python functions:min, max and remove are already O(n) +Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ diff --git a/traversals/binary_tree_traversals.py b/traversals/binary_tree_traversals.py index 31a73ae0c6a4..c522ecebc0ff 100644 --- a/traversals/binary_tree_traversals.py +++ b/traversals/binary_tree_traversals.py @@ -1,5 +1,5 @@ """ -This is pure python implementation of tree traversal algorithms +This is pure Python implementation of tree traversal algorithms """ import queue from typing import List diff --git a/web_programming/emails_from_url.py b/web_programming/emails_from_url.py index fba9f769bace..01dee274f015 100644 --- a/web_programming/emails_from_url.py +++ b/web_programming/emails_from_url.py @@ -51,8 +51,6 @@ def get_domain_name(url: str) -> str: # Get sub domain name (sub.example.com) def get_sub_domain_name(url: str) -> str: """ - This function get sub domin name - >>> get_sub_domain_name("https://a.b.c.d/e/f?g=h,i=j#k") 'a.b.c.d' >>> get_sub_domain_name("Not a URL!")