diff --git a/BFS/python/bfs.py b/BFS/python/bfs.py index 842e8c18..cbb4763f 100644 --- a/BFS/python/bfs.py +++ b/BFS/python/bfs.py @@ -10,8 +10,7 @@ def addEdge(self, u, v): self.graph[u].append(v) def BFS(self, node): - queue = [] - queue.append(node) + queue = [node] self.visited[node] = True while queue: @@ -19,10 +18,10 @@ def BFS(self, node): print(currentNode) children = self.graph[currentNode] - for i in range(len(children)): - if not self.visited[children[i]]: - queue.append(children[i]) - self.visited[children[i]] = True + for child in children: + if not self.visited[child]: + queue.append(child) + self.visited[child] = True if __name__ == '__main__': diff --git a/BST/python/BinarySearchTree.py b/BST/python/BinarySearchTree.py index e7151b66..fc569bc8 100644 --- a/BST/python/BinarySearchTree.py +++ b/BST/python/BinarySearchTree.py @@ -23,69 +23,71 @@ def isEmpty(self): return self._size == 0 def populateTree(self): - for i in range(len(self.arr)): - self.insert(self.arr[i]) + for item in self.arr: + self.insert(item) def insert(self, value): - if type(value) == self._dataType: - itemNum = self._size - newNode = Node(value, type(value), itemNum, None, None, None) - if (self._root is None): - self._root = newNode - self._size += 1 - return + if type(value) != self._dataType: + return + itemNum = self._size + newNode = Node(value, type(value), itemNum, None, None, None) + if (self._root is None): + self._root = newNode + self._size += 1 + return + + pointer = self._root + currentVal = pointer.getData() + while True: + if value < currentVal: + if pointer.getLeft() is None: + newNode.setParent(pointer) + pointer.setLeft(newNode) + self._size += 1 + return + else: + pointer = pointer.getLeft() + currentVal = pointer.getData() - pointer = self._root - currentVal = pointer.getData() - while True: - if value < currentVal: - if pointer.getLeft() is None: - newNode.setParent(pointer) - pointer.setLeft(newNode) - self._size += 1 - return - else: - pointer = pointer.getLeft() - currentVal = pointer.getData() - - elif value > currentVal: - if pointer.getRight() is None: - newNode.setParent(pointer) - pointer.setRight(newNode) - self._size += 1 - return - else: - pointer = pointer.getRight() - currentVal = pointer.getData() - - elif value == currentVal: - print("Value already exists in BST.") + elif value > currentVal: + if pointer.getRight() is None: + newNode.setParent(pointer) + pointer.setRight(newNode) + self._size += 1 return + else: + pointer = pointer.getRight() + currentVal = pointer.getData() + + elif value == currentVal: + print("Value already exists in BST.") + return def search(self, value): - if type(value) == self._dataType: - if (self._root is None): - return False + if type(value) != self._dataType: + return + if (self._root is None): + return False - pointer = self._root - currentVal = pointer.getData() - while True: - if value < currentVal: - if pointer.getLeft() is None: - return False + pointer = self._root + currentVal = pointer.getData() + while True: + if value < currentVal: + if pointer.getLeft() is None: + return False - pointer = pointer.getLeft() - currentVal = pointer.getData() + pointer = pointer.getLeft() + currentVal = pointer.getData() - elif value > currentVal: - if pointer.getRight() is None: - return False + elif value > currentVal: + if pointer.getRight() is None: + return False - pointer = pointer.getRight() - currentVal = pointer.getData() + pointer = pointer.getRight() + currentVal = pointer.getData() - elif value == currentVal: - return pointer.getItemNum() + elif value == currentVal: + return pointer.getItemNum() def inOrderTraversal(self, node): if node is not None: @@ -94,7 +96,7 @@ def inOrderTraversal(self, node): self.inOrderTraversal(node.getRight()) def getSorted(self): - self.sorted = list() + self.sorted = [] self.inOrderTraversal(self._root) return self.sorted diff --git a/BackTracking/Hamilton Path/hamilton.py b/BackTracking/Hamilton Path/hamilton.py index e9e9de02..23af9bc7 100644 --- a/BackTracking/Hamilton Path/hamilton.py +++ b/BackTracking/Hamilton Path/hamilton.py @@ -20,15 +20,11 @@ def isSafe(self, v, pos, path): def hamCycleUtil(self, path, pos): # base case: if all vertices are - # included in the path + # included in the path if pos == self.V: # Last vertex must be adjacent to the - # first vertex in path to make a cyle - if self.graph[path[pos - 1]][path[0]] == 1: - return True - else: - return False - + # first vertex in path to make a cyle + return self.graph[path[pos - 1]][path[0]] == 1 for v in range(1, self.V): if self.isSafe(v, pos, path) is True: diff --git a/BackTracking/RatInAMaze/ratmaze.py b/BackTracking/RatInAMaze/ratmaze.py index 82517bc1..5682d5e2 100644 --- a/BackTracking/RatInAMaze/ratmaze.py +++ b/BackTracking/RatInAMaze/ratmaze.py @@ -16,9 +16,7 @@ def printSolution(sol): # A utility function to check if x,y is valid # index for N*N Maze def isSafe(maze, x, y): - if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: - return True - return False + return x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1 def solveMaze(maze): diff --git a/BitManipulation/count_ones/count_ones.py b/BitManipulation/count_ones/count_ones.py index 62ed4b77..aa1963e4 100644 --- a/BitManipulation/count_ones/count_ones.py +++ b/BitManipulation/count_ones/count_ones.py @@ -3,7 +3,7 @@ def count_ones(n: int): while n: if n & 1: count += 1 - n = n // 2 + n //= 2 return count diff --git a/DP/Fibonacci/fibonacci.py b/DP/Fibonacci/fibonacci.py index 52f13a82..5194b62a 100644 --- a/DP/Fibonacci/fibonacci.py +++ b/DP/Fibonacci/fibonacci.py @@ -1,6 +1,6 @@ # DP Approach for Fibonacci series -ans = dict() +ans = {} def fibo(i): diff --git a/Graph/DijkstrasSPT/python/Dadjacencylist.py b/Graph/DijkstrasSPT/python/Dadjacencylist.py index 9ea4da71..88daa32e 100644 --- a/Graph/DijkstrasSPT/python/Dadjacencylist.py +++ b/Graph/DijkstrasSPT/python/Dadjacencylist.py @@ -11,8 +11,7 @@ def __init__(self): self.pos = [] def newMinHeapNode(self, v, dist): - minHeapNode = [v, dist] - return minHeapNode + return [v, dist] # A utility function to swap two nodes # of min heap. Needed for min heapify @@ -82,9 +81,7 @@ def decreaseKey(self, v, dist): # vertex 'v' is in min heap or not def isInMinHeap(self, v): - if self.pos[v] < self.size: - return True - return False + return self.pos[v] < self.size def printArr(dist, n): diff --git a/Hashing/3_Sum/threeSum.py b/Hashing/3_Sum/threeSum.py index c67090fa..74439627 100644 --- a/Hashing/3_Sum/threeSum.py +++ b/Hashing/3_Sum/threeSum.py @@ -2,13 +2,14 @@ Author: Tushar Nitave ''' + nums = [-1, 0, 1, 2, -1, -4] hashTable = [] result = [] # result containing duplicate values finalresult = [] # stores final result without duplicate values -for i in range(0, len(nums) - 2): +for i in range(len(nums) - 2): for j in range(i + 1, len(nums) - 1): x = -(nums[i] + nums[j]) @@ -20,9 +21,9 @@ else: hashTable.append(nums[j]) -for i in range(len(result)): - result[i].sort() - if not result[i] in finalresult: - finalresult.append(result[i]) +for item in result: + item.sort() + if item not in finalresult: + finalresult.append(item) print(finalresult) diff --git a/Math/Prime/python/prime.py b/Math/Prime/python/prime.py index 8f207780..2753c927 100644 --- a/Math/Prime/python/prime.py +++ b/Math/Prime/python/prime.py @@ -5,10 +5,7 @@ def is_prime(number): if (number <= 1): return False - for i in range(2, 1 + int(math.sqrt(number))): - if (number % i) == 0: - return False - return True + return all(number % i != 0 for i in range(2, 1 + int(math.sqrt(number)))) number = input("Enter a number : ") diff --git a/Math/Russain Peasants Algorithm/python/russian-peasants-algorithm.py b/Math/Russain Peasants Algorithm/python/russian-peasants-algorithm.py index b75ca95d..c9594a6c 100644 --- a/Math/Russain Peasants Algorithm/python/russian-peasants-algorithm.py +++ b/Math/Russain Peasants Algorithm/python/russian-peasants-algorithm.py @@ -6,13 +6,13 @@ def multiply(a,b): else: left = b right = a - + prod = 0 - + while left > 0: # Loop till you reach 1 if left%2 != 0: # Add the value to product variable if the left column value is odd - prod = prod + right - + prod += right + left = left >> 1 # Right shift right = right << 1 # Left Shift diff --git a/Math/collatz_conjecture/Python/collatz_conjecture.py b/Math/collatz_conjecture/Python/collatz_conjecture.py index 908db8da..1868fe88 100644 --- a/Math/collatz_conjecture/Python/collatz_conjecture.py +++ b/Math/collatz_conjecture/Python/collatz_conjecture.py @@ -1,12 +1,8 @@ def collatz(n): seq = [n] while n > 1: - if n%2 == 1: - n = n*3 + 1 - seq.append(n) - else: - n = n/2 - seq.append(n) + n = n * 3 + 1 if n % 2 == 1 else n / 2 + seq.append(n) return seq if __name__ == "__main__" : diff --git a/Math/eulers_totient_function/python/eulers_totient.py b/Math/eulers_totient_function/python/eulers_totient.py index 49bcbd65..9003b86d 100644 --- a/Math/eulers_totient_function/python/eulers_totient.py +++ b/Math/eulers_totient_function/python/eulers_totient.py @@ -5,10 +5,4 @@ def gcd(a, b): return gcd(b % a, a) def phi(n): - res = 1 - - for i in range(2, n): - if gcd(i, n) == 1: - res += 1 - - return res \ No newline at end of file + return 1 + sum(1 for i in range(2, n) if gcd(i, n) == 1) \ No newline at end of file diff --git a/Math/lowest_common_multiple/lcm.py b/Math/lowest_common_multiple/lcm.py index bd2eef75..66137486 100644 --- a/Math/lowest_common_multiple/lcm.py +++ b/Math/lowest_common_multiple/lcm.py @@ -1,11 +1,11 @@ -def lcm(num1, num2): - """Returns the lowest common multiple of two given integers.""" - temp_num = num1 - while (temp_num % num2) != 0: - temp_num += num1 - return temp_num - -if __name__ == "__main__": - print lcm(3, 9) # output is 9 - print lcm(24, 36) # output is 72 - print lcm(12, 80) # output is 240 +def lcm(num1, num2): + """Returns the lowest common multiple of two given integers.""" + temp_num = num1 + while (temp_num % num2) != 0: + temp_num += num1 + return temp_num + +if __name__ == "__main__": + print lcm(3, 9) # output is 9 + print lcm(24, 36) # output is 72 + print lcm(12, 80) # output is 240 diff --git a/NetworkFlow/EdmundKarp/edmund_karp.py b/NetworkFlow/EdmundKarp/edmund_karp.py index 04882f97..4252dd4c 100644 --- a/NetworkFlow/EdmundKarp/edmund_karp.py +++ b/NetworkFlow/EdmundKarp/edmund_karp.py @@ -16,12 +16,11 @@ def EdmondsKarp(E, C, s, t): P[s] = -2 M = [0 for x in range(n)] M[s] = decimal.Decimal('Infinity') - BFSq = [] - BFSq.append(s) + BFSq = [s] pathFlow, P = BFSEK(E, C, s, t, F, P, M, BFSq) if pathFlow == 0: break - flow = flow + pathFlow + flow += pathFlow v = t while v != s: u = P[v] diff --git a/Search/FibonacciSearch/fibonacci_search.py b/Search/FibonacciSearch/fibonacci_search.py index 35abd648..0518e6e0 100644 --- a/Search/FibonacciSearch/fibonacci_search.py +++ b/Search/FibonacciSearch/fibonacci_search.py @@ -44,9 +44,7 @@ def fibonacci_search(arr, x, n): if __name__ == "__main__": n = int(input("Enter the number of elements: ")) print("Enter the elements each line") - arr = [] - for i in range(n): - arr.append(int(input())) + arr = [int(input()) for _ in range(n)] x = int(input("Enter element to be searched: ")) idx = fibonacci_search(arr, x, n) if idx == -1: diff --git a/Search/LinearSearch/linear_search.py b/Search/LinearSearch/linear_search.py index 153e5e6e..63efd326 100644 --- a/Search/LinearSearch/linear_search.py +++ b/Search/LinearSearch/linear_search.py @@ -4,11 +4,9 @@ @author: KARAN """ -numbers = [] -n = int(input("Enter the total number of elements : ")) -for i in range(n): - numbers.append(int(input("Enter a number : "))) +n = int(input("Enter the total number of elements : ")) +numbers = [int(input("Enter a number : ")) for _ in range(n)] key = int(input("Enter the number you wanna find in the list : ")) found = False for i in range(n): diff --git a/Search/hashing/2_Sum/sum_pair.py b/Search/hashing/2_Sum/sum_pair.py index bb286470..d04da52c 100644 --- a/Search/hashing/2_Sum/sum_pair.py +++ b/Search/hashing/2_Sum/sum_pair.py @@ -1,11 +1,11 @@ def print_pairs(arr, sum): s = set() - for i in range(0, len(arr)): - temp = sum - arr[i] + for item in arr: + temp = sum - item if temp >= 0 and temp in s: - print("Pair with the given sum is", arr[i], "and", temp) - s.add(arr[i]) + print("Pair with the given sum is", item, "and", temp) + s.add(item) if __name__ == "__main__": diff --git a/Sorting/CountingSort/python/CountingSort.py b/Sorting/CountingSort/python/CountingSort.py index 9ee98e62..f9479c2e 100644 --- a/Sorting/CountingSort/python/CountingSort.py +++ b/Sorting/CountingSort/python/CountingSort.py @@ -7,7 +7,7 @@ def countingSort(arr, k): count[a] += 1 i = 0 for a in range(m): - for c in range(count[a]): + for _ in range(count[a]): arr[i] = a i += 1 return arr diff --git a/Sorting/MergeSort/python/MergeSort.py b/Sorting/MergeSort/python/MergeSort.py index 2275d1ae..3e74bdfb 100755 --- a/Sorting/MergeSort/python/MergeSort.py +++ b/Sorting/MergeSort/python/MergeSort.py @@ -12,7 +12,7 @@ def mergeSort(self, a): return a def merge(self, left, right): - output = list() + output = [] leftCount, rightCount = 0, 0 while leftCount < len(left) or rightCount < len(right): if leftCount < len(left) and rightCount < len(right): diff --git a/String/Anagram/Group_Anagrams/group_anagram.py b/String/Anagram/Group_Anagrams/group_anagram.py index 2a0a4502..42996dbf 100644 --- a/String/Anagram/Group_Anagrams/group_anagram.py +++ b/String/Anagram/Group_Anagrams/group_anagram.py @@ -13,12 +13,9 @@ arrFinal = [] i = 0 for x in inp: - arrPrint = [] - for b in inp: - if (is_anagram.is_anagram(str(x), str(b))): - arrPrint.append(b) + arrPrint = [b for b in inp if is_anagram.is_anagram(str(x), str(b))] arrFinal.append(arrPrint) - i = i + 1 + i += 1 aux = arrFinal[0][0] for i, j in enumerate(arrFinal[:-1]): diff --git a/String/Anagram/Group_Anagrams/is_anagram.py b/String/Anagram/Group_Anagrams/is_anagram.py index 3431c8d0..3ccabec6 100644 --- a/String/Anagram/Group_Anagrams/is_anagram.py +++ b/String/Anagram/Group_Anagrams/is_anagram.py @@ -6,22 +6,15 @@ def is_anagram(str1, str2): chars2 = get_alphabet(str2.lower()) # Check if both strings contain the same characters in the same amounts - if chars1 == chars2: - return True - else: - return False + return chars1 == chars2 def get_alphabet(string): """Creates a dictionary containing a count of the number of times each alphanumeric character in string is used.""" """E.g. get_alphabet("Hello") would return {'H':1, 'e':1, 'l':2, 'o':1}""" - alphabet = dict() + alphabet = {} for c in string: if c.isalnum(): - if c in alphabet: - alphabet[c] = alphabet[c] + 1 - else: - alphabet[c] = 1 - + alphabet[c] = alphabet[c] + 1 if c in alphabet else 1 return alphabet diff --git a/String/Anagram/is_anagram.py b/String/Anagram/is_anagram.py index d706c7b9..ad50a217 100644 --- a/String/Anagram/is_anagram.py +++ b/String/Anagram/is_anagram.py @@ -16,10 +16,7 @@ def is_anagram(a: str, b: str): elif 'A' <= b[i] <= 'Z': count2[ord(b[i]) - ord('A')] -= 1 - if any(count) or any(count2): - return False - - return True + return not any(count) and not any(count2) if __name__ == '__main__': diff --git a/String/Balanced Parentheses/balanced_parantheses.py b/String/Balanced Parentheses/balanced_parantheses.py index 02a7ac05..b4b9d046 100644 --- a/String/Balanced Parentheses/balanced_parantheses.py +++ b/String/Balanced Parentheses/balanced_parantheses.py @@ -11,7 +11,7 @@ def is_balanced(expr): stack = [] n = len(expr) - for i in range(0, n): + for i in range(n): if (expr[i] in opening_parantheses): stack.append(expr[i]) elif (expr[i] in closing_parantheses): @@ -20,7 +20,7 @@ def is_balanced(expr): if (stack.pop() != matching_paranthesis): return False - return True if len(stack) == 0 else False + return True if not stack else False def main(): diff --git a/String/String Matching/rabin_karp_matcher.py b/String/String Matching/rabin_karp_matcher.py index c91a1c6d..9082e0ad 100644 --- a/String/String Matching/rabin_karp_matcher.py +++ b/String/String Matching/rabin_karp_matcher.py @@ -28,7 +28,7 @@ def rabin_karp_matcher(T, P, d, q): p = 0 t = 0 # preprocessing - for i in range(m - 1): + for _ in range(m - 1): h = (h * d) % q for i in range(m): p = (d * p + ord(P[i])) % q