diff --git a/algorithms/bit_manipulation/sum_of_two_integers.py b/algorithms/bit_manipulation/sum_of_two_integers.py index c8203c5a..b3afa9ef 100644 --- a/algorithms/bit_manipulation/sum_of_two_integers.py +++ b/algorithms/bit_manipulation/sum_of_two_integers.py @@ -18,5 +18,4 @@ def getSum(a, b): carry = carry << 1 a = diff b = carry - if b > 0: return (a & mask) - else: return a \ No newline at end of file + return (a & mask) if b > 0 else a \ No newline at end of file diff --git a/algorithms/dynamic_programming/01_knapsack.py b/algorithms/dynamic_programming/01_knapsack.py index 652c65e9..38fc782a 100644 --- a/algorithms/dynamic_programming/01_knapsack.py +++ b/algorithms/dynamic_programming/01_knapsack.py @@ -7,7 +7,7 @@ def knapsack(values, weights, total): # rows are the number of items # columns are the values of weights required - t = [[0 for i in range(cols)] for i in range(rows)] + t = [[0 for _ in range(cols)] for _ in range(rows)] for i in range(1, rows): for j in range(1, cols): diff --git a/algorithms/dynamic_programming/Z_Algorithm.py b/algorithms/dynamic_programming/Z_Algorithm.py index 6af4c894..1e58270e 100644 --- a/algorithms/dynamic_programming/Z_Algorithm.py +++ b/algorithms/dynamic_programming/Z_Algorithm.py @@ -18,13 +18,9 @@ def z_function(text:str , size:int): z[i] = min(r - i + 1 , z[i - l]) while i + z[i] < len(text) and text[z[i]] == text[i + z[i]]: z[i] += 1 - + if i + z[i] - 1 > r: l = i r = i + z[i] - 1 - - res = [] - for i in range(size , len(text)): - if z[i] == size: - res.append(i - size - 1) - return res \ No newline at end of file + + return [i - size - 1 for i in range(size , len(text)) if z[i] == size] \ No newline at end of file diff --git a/algorithms/dynamic_programming/longest_common_subsequence.py b/algorithms/dynamic_programming/longest_common_subsequence.py index 2c60beda..a38e8b1a 100644 --- a/algorithms/dynamic_programming/longest_common_subsequence.py +++ b/algorithms/dynamic_programming/longest_common_subsequence.py @@ -2,7 +2,7 @@ def lcs(s1, s2): cols = len(s1) + 1 rows = len(s2) + 1 - t = [[0 for i in range(cols)] for i in range(rows)] + t = [[0 for _ in range(cols)] for _ in range(rows)] max_length = 0 diff --git a/algorithms/dynamic_programming/longest_common_substring.py b/algorithms/dynamic_programming/longest_common_substring.py index bf6995ad..9f5ad9ba 100644 --- a/algorithms/dynamic_programming/longest_common_substring.py +++ b/algorithms/dynamic_programming/longest_common_substring.py @@ -2,7 +2,7 @@ def lcs(s1, s2): cols = len(s1) + 1 rows = len(s2) + 1 - t = [[0 for i in range(cols)] for i in range(rows)] + t = [[0 for _ in range(cols)] for _ in range(rows)] max_length = 0 diff --git a/algorithms/dynamic_programming/longest_consecutive_subsequence.py b/algorithms/dynamic_programming/longest_consecutive_subsequence.py index 742ef4b7..9a15812b 100644 --- a/algorithms/dynamic_programming/longest_consecutive_subsequence.py +++ b/algorithms/dynamic_programming/longest_consecutive_subsequence.py @@ -13,20 +13,16 @@ """ def find_seq(arr, n): - s = set() - - for num in arr: - s.add(num) - + s = set(arr) ans = 0 elements = [] for i in range(n): - temp = [] - if arr[i] - 1 not in s: j = arr[i] + temp = [] + while j in s: temp.append(j) j += 1 diff --git a/algorithms/dynamic_programming/longest_palindromic_substring.py b/algorithms/dynamic_programming/longest_palindromic_substring.py index 251d2e7f..03815549 100644 --- a/algorithms/dynamic_programming/longest_palindromic_substring.py +++ b/algorithms/dynamic_programming/longest_palindromic_substring.py @@ -1,6 +1,6 @@ def longest_palindromic_substring_DP(s): - S = [[False for i in range(len(s))] for j in range(len(s))] + S = [[False for _ in range(len(s))] for _ in range(len(s))] max_palindrome = "" @@ -23,10 +23,10 @@ def longest_palindromic_substring_expansion(s): max_palindrome = "" for i in range(len(s) * 2 - 1): + # This is when you are "on" an actual character + # o = offset, ind = current character + o = 0 if i % 2 == 0: - # This is when you are "on" an actual character - # o = offset, ind = current character - o = 0 ind = i // 2 while ind + o < len(s) and ind - o >= 0: if(s[ind + o] != s[ind - o]): @@ -35,9 +35,6 @@ def longest_palindromic_substring_expansion(s): max_palindrome = s[ind-o:ind+o + 1] o += 1 else: - # This is when you are "in the middle of" two characters - # o = offset, sind = start char, eind = end char - o = 0 sind = i // 2 eind = i // 2 + 1 while sind - o >= 0 and eind + o < len(s): @@ -54,4 +51,4 @@ def longest_palindromic_substring_expansion(s): ans_DP = longest_palindromic_substring_DP(input_string) ans_expansion = longest_palindromic_substring_expansion(input_string) -print("DP Solution: {}, Expansion Solution: {}".format(ans_DP, ans_expansion)) +print(f"DP Solution: {ans_DP}, Expansion Solution: {ans_expansion}") diff --git a/algorithms/dynamic_programming/longest_subarray_sum_divisible_by_k.py b/algorithms/dynamic_programming/longest_subarray_sum_divisible_by_k.py index 4d691f59..b5df9652 100644 --- a/algorithms/dynamic_programming/longest_subarray_sum_divisible_by_k.py +++ b/algorithms/dynamic_programming/longest_subarray_sum_divisible_by_k.py @@ -39,15 +39,14 @@ def find_length(arr, k): for i in range(0, len(mod_arr)): if mod_arr[i] == 0: length += 1 + elif mod_arr[i] in hash_table: + if length < (i - mod_arr[i]): + length = i - mod_arr[i] + start = mod_arr[i] + end = i - 1 # i-1 because the current number is not to considered as it makes the sum not divisible by k + else: - if mod_arr[i] not in hash_table: - hash_table[mod_arr[i]] = i - else: - if length < (i - mod_arr[i]): - length = i - mod_arr[i] - start = mod_arr[i] - end = i - 1 # i-1 because the current number is not to considered as it makes the sum not divisible by k - + hash_table[mod_arr[i]] = i return length, arr[start:end+1] diff --git a/algorithms/greedy/activity_selection.py b/algorithms/greedy/activity_selection.py index 374ad563..334cf5e9 100644 --- a/algorithms/greedy/activity_selection.py +++ b/algorithms/greedy/activity_selection.py @@ -7,16 +7,11 @@ def find_activities(arr): n = len(arr) - selected = [] - arr.sort(key = lambda x: x[1]) i = 0 - # since it is a greedy algorithm, the first acitivity is always - # selected because it is the most optimal choice at that point - selected.append(arr[i]) - + selected = [arr[i]] for j in range(1, n): start_time_next_activity = arr[j][0] end_time_prev_activity = arr[i][1] diff --git a/algorithms/greedy/cost_of_tiles.py b/algorithms/greedy/cost_of_tiles.py index 05fde8da..bfaf1ac6 100644 --- a/algorithms/greedy/cost_of_tiles.py +++ b/algorithms/greedy/cost_of_tiles.py @@ -18,7 +18,7 @@ def cost(arr, A, B): for i in range(n): j = 0 - + while j < m: if arr[i][j] == '*': # tile is already there j += 1 @@ -26,12 +26,11 @@ def cost(arr, A, B): if j == m - 1: # if j is pointing to last tile, you can use only 1*1 tile ans += A + elif arr[i][j+1] == '.': + ans += min(2 * A, B) + j += 1 else: - if arr[i][j+1] == '.': - ans += min(2 * A, B) - j += 1 - else: - ans += A + ans += A j += 1 diff --git a/algorithms/greedy/dijkstra_greedy.py b/algorithms/greedy/dijkstra_greedy.py index 32aaba6d..e6fa1613 100644 --- a/algorithms/greedy/dijkstra_greedy.py +++ b/algorithms/greedy/dijkstra_greedy.py @@ -1,23 +1,19 @@ def dijkstra(graph, start, end): - shortest_distance = {} - non_visited_nodes = {} - for i in graph: - non_visited_nodes[i] = graph[i] - + non_visited_nodes = {i: graph[i] for i in graph} infinit = float('inf') - for no in non_visited_nodes: - shortest_distance[no] = infinit + shortest_distance = {no: infinit for no in non_visited_nodes} shortest_distance[start] = 0 - + while non_visited_nodes != {}: shortest_extracted_node = None for i in non_visited_nodes: - if shortest_extracted_node is None: - shortest_extracted_node = i - elif shortest_distance[i] < shortest_distance[shortest_extracted_node]: + if ( + shortest_extracted_node is None + or shortest_distance[i] + < shortest_distance[shortest_extracted_node] + ): shortest_extracted_node = i - for no_v, Weight in graph[shortest_extracted_node]: if Weight + shortest_distance[shortest_extracted_node] < shortest_distance[no_v]: shortest_distance[no_v] = Weight + shortest_distance[shortest_extracted_node] @@ -31,7 +27,7 @@ def dijkstra(graph, start, end): cities, origin, destiny = map(int, input().split()) graph = {i:[] for i in range(1, cities+1)} -for i in range(cities-1): +for _ in range(cities-1): u, v, w = map(int, input().split()) graph[v].append((u, w)) graph[u].append((v, w)) \ No newline at end of file diff --git a/algorithms/greedy/min_platforms.py b/algorithms/greedy/min_platforms.py index fd372f0a..6a0d14cb 100644 --- a/algorithms/greedy/min_platforms.py +++ b/algorithms/greedy/min_platforms.py @@ -21,7 +21,7 @@ def find_platforms(arrival, departure): plat += 1 i += 1 - elif arrival[i] > departure[j]: + else: plat -= 1 j += 1 diff --git a/algorithms/math/divisors.py b/algorithms/math/divisors.py index ea923837..a30e840f 100644 --- a/algorithms/math/divisors.py +++ b/algorithms/math/divisors.py @@ -3,46 +3,28 @@ class divisors: def findAllDivisors(self, n): - result = list() - - for i in range(1, n+1): - if (n%i == 0): - result.append(i) - - return result + return [i for i in range(1, n+1) if (n%i == 0)] def divisorsCount(self, n): divs = self.findAllDivisors(n) return len(divs) def oddFactors(self, n): - result = list() - - for i in range(1, n+1): - if (n%i == 0 and i%2==1): - result.append(i) - - return result + return [i for i in range(1, n+1) if (n%i == 0 and i%2==1)] def oddFactorsSum(self, n): divs = self.evenFactors(n) return sum(divs) def evenFactors(self, n): - result = list() - - for i in range(1, n+1): - if (n%i == 0 and i%2==0): - result.append(i) - - return result + return [i for i in range(1, n+1) if (n%i == 0 and i%2==0)] def evenFactorsSum(self, n): divs = self.evenFactors(n) return sum(divs) def primeFactors(self, n): - result = list() + result = [] while n % 2 == 0: result.append(2) @@ -52,10 +34,10 @@ def primeFactors(self, n): while n % i== 0: result.append(i) n = n / i - + if n > 2: result.append(n) - + return result def primeFactorsSum(self, n): diff --git a/algorithms/math/factorial_iterative.py b/algorithms/math/factorial_iterative.py index d722ec92..4c84c9d9 100644 --- a/algorithms/math/factorial_iterative.py +++ b/algorithms/math/factorial_iterative.py @@ -6,9 +6,8 @@ def factorial(number): if number == 0: return 1 - else: - for num in range(1, number+1): - answer = answer * num + for num in range(1, number+1): + answer = answer * num return answer if __name__ == '__main__': diff --git a/algorithms/math/factorial_recursive.py b/algorithms/math/factorial_recursive.py index ed5f3b38..d0ca50b0 100644 --- a/algorithms/math/factorial_recursive.py +++ b/algorithms/math/factorial_recursive.py @@ -2,12 +2,7 @@ def factorial(number): - if number == 0 or number == 1: - return 1 - - answer = number * factorial(number - 1) - - return answer + return 1 if number in [0, 1] else number * factorial(number - 1) if __name__ == '__main__': diff --git a/algorithms/math/greatest_common_divisor.py b/algorithms/math/greatest_common_divisor.py index 53e70f1d..96c2cbf4 100644 --- a/algorithms/math/greatest_common_divisor.py +++ b/algorithms/math/greatest_common_divisor.py @@ -23,10 +23,7 @@ def gcd(x, y): def gcd(x, y): if x == 0: return y - if y == 0: - return x - - return gcd(y, x % y) + return x if y == 0 else gcd(y, x % y) # Iterative optimized def gcd(x, y): diff --git a/algorithms/math/number_convertion.py b/algorithms/math/number_convertion.py index e119eb9c..d589bbf9 100644 --- a/algorithms/math/number_convertion.py +++ b/algorithms/math/number_convertion.py @@ -18,10 +18,7 @@ def verify_base(x): try: return int(x) except: - if x in bases: - return bases[x] - else: - return default + return bases[x] if x in bases else default def decimal_value(x): @@ -91,10 +88,10 @@ def convert(n, from_base, to_base): decimal_number += (multi * decimal_value(n[i])) multi *= from_base - if(to_base == 10): + if (to_base == 10): decimal_number = str(decimal_number) - if(negative): - decimal_number = '-' + decimal_number + if negative: + decimal_number = f'-{decimal_number}' return decimal_number @@ -105,8 +102,8 @@ def convert(n, from_base, to_base): result = to_special_caracter(value) + result decimal_number = int((decimal_number - value)/to_base) - if(negative): - result = '-' + result + if negative: + result = f'-{result}' return result diff --git a/algorithms/math/perfect_square.py b/algorithms/math/perfect_square.py index 40e817bb..8202ee8b 100644 --- a/algorithms/math/perfect_square.py +++ b/algorithms/math/perfect_square.py @@ -8,12 +8,9 @@ def is_perfect_square(num): :rtype: bool """ i = 0 - while i * i < num: + while i**2 < num: i += 1 - if i * i == num: - return True - else: - return False + return i**2 == num # Test diff --git a/algorithms/math/recursive_fibonacci.py b/algorithms/math/recursive_fibonacci.py index eb319cd9..47551ddd 100644 --- a/algorithms/math/recursive_fibonacci.py +++ b/algorithms/math/recursive_fibonacci.py @@ -12,7 +12,7 @@ def rec_fib(n): return rec_fib(n-1)+rec_fib(n-2) def binary_rec_fib(n): - if n == 2 or n == 1: + if n in [2, 1]: return 1 elif n == 0: return 0 diff --git a/algorithms/math/sieve_of_eratosthenes.py b/algorithms/math/sieve_of_eratosthenes.py index 929d17e0..aeed4956 100644 --- a/algorithms/math/sieve_of_eratosthenes.py +++ b/algorithms/math/sieve_of_eratosthenes.py @@ -9,8 +9,7 @@ def sieve(n): for i in range(2, n+1): if i not in prime_list: print(i) - for j in range(i*i, n+1, i): - prime_list.append(j) + prime_list.extend(iter(range(i*i, n+1, i))) if __name__ == '__main__': diff --git a/algorithms/miscellaneous/front_and_back_search.py b/algorithms/miscellaneous/front_and_back_search.py index 04e129ac..fd982df0 100644 --- a/algorithms/miscellaneous/front_and_back_search.py +++ b/algorithms/miscellaneous/front_and_back_search.py @@ -12,15 +12,14 @@ def front_and_back_search(lst, item): u=None if rear>front: return False - else: - while rear<=front: - if item==lst[rear] or item==lst[front]: - u='' - return True ##item found - elif item!=lst[rear] and item!=lst[front]: - if item > lst[rear]: - rear=rear+1 - elif item < lst[front]: - front=front-1 - if u==None: - return False + while rear<=front: + if item in [lst[rear], lst[front]]: + u='' + return True ##item found + else: + if item > lst[rear]: + rear += 1 + elif item < lst[front]: + front=front-1 + if u is None: + return False diff --git a/algorithms/miscellaneous/luhn_algorithm.py b/algorithms/miscellaneous/luhn_algorithm.py index e6d4b20d..bfd2823d 100644 --- a/algorithms/miscellaneous/luhn_algorithm.py +++ b/algorithms/miscellaneous/luhn_algorithm.py @@ -27,16 +27,8 @@ def check_luhn(card_number): is_parity = False for digit in range(card_len - 1, -1, -1): - if is_parity: - cal = int(card_number[digit]) * 2 - else: - cal = int(card_number[digit]) - - if cal > 9: - check_sum += cal - 9 - else: - check_sum += cal - + cal = int(card_number[digit]) * 2 if is_parity else int(card_number[digit]) + check_sum += cal - 9 if cal > 9 else cal is_parity = not is_parity return check_sum % 10 == 0 diff --git a/algorithms/sorting/merge_sort.py b/algorithms/sorting/merge_sort.py index 8dbf1d37..0f02198c 100644 --- a/algorithms/sorting/merge_sort.py +++ b/algorithms/sorting/merge_sort.py @@ -10,36 +10,37 @@ """ def merge_sort(arr): - if len(arr) >1: - mid = len(arr)//2 #Finding the mid of the array - L = arr[:mid] # Dividing the array elements - R = arr[mid:] # into 2 halves - - merge_sort(L) # Sorting the first half - merge_sort(R) # Sorting the second half - - i = j = k = 0 - - # Copy data to temp arrays L[] and R[] - while i < len(L) and j < len(R): - if L[i] < R[j]: - arr[k] = L[i] - i+=1 - else: - arr[k] = R[j] - j+=1 - k+=1 - - # Checking if any element was left - while i < len(L): + if len(arr) <= 1: + return + mid = len(arr)//2 #Finding the mid of the array + L = arr[:mid] # Dividing the array elements + R = arr[mid:] # into 2 halves + + merge_sort(L) # Sorting the first half + merge_sort(R) # Sorting the second half + + i = j = k = 0 + + # Copy data to temp arrays L[] and R[] + while i < len(L) and j < len(R): + if L[i] < R[j]: arr[k] = L[i] i+=1 - k+=1 - - while j < len(R): + else: arr[k] = R[j] j+=1 - k+=1 + k+=1 + + # Checking if any element was left + while i < len(L): + arr[k] = L[i] + i+=1 + k+=1 + + while j < len(R): + arr[k] = R[j] + j+=1 + k+=1 test_array = [10,30,20,100,40,80,90,210,34] diff --git a/algorithms/sorting/permutation_sort.py b/algorithms/sorting/permutation_sort.py index 4912ff9e..c7a56bf1 100644 --- a/algorithms/sorting/permutation_sort.py +++ b/algorithms/sorting/permutation_sort.py @@ -13,10 +13,7 @@ def bogo_sort(a): def is_sorted(a): n = len(a) - for i in range(0, n - 1): - if (a[i] > a[i + 1]): - return False - return True + return all(a[i] <= a[i + 1] for i in range(0, n - 1)) # To generate permuatation of the array @@ -32,5 +29,5 @@ def shuffle(a): a = [3, 2, 4, 1, 0, 5] bogo_sort(a) print("Sorted array :") -for i in range(len(a)): - print("%d" % a[i]), +for item in a: + (print("%d" % item), ) diff --git a/algorithms/sorting/select_sort.py b/algorithms/sorting/select_sort.py index 8ba2cad7..59d67f91 100644 --- a/algorithms/sorting/select_sort.py +++ b/algorithms/sorting/select_sort.py @@ -15,10 +15,10 @@ def find_smallest(arr): def selection_sort(arr): new_arr = [] - for i in range(len(arr)): + for _ in range(len(arr)): smallest = find_smallest(arr) new_arr.append(arr.pop(smallest)) - + return new_arr array = [100, 5, 72, 41, 80, 1, 99, 36, 27, 78] diff --git a/algorithms/sorting/shell_sort.py b/algorithms/sorting/shell_sort.py index 27269ec7..499139fc 100644 --- a/algorithms/sorting/shell_sort.py +++ b/algorithms/sorting/shell_sort.py @@ -9,7 +9,7 @@ def shell_sort(arr): # Start with a big gap, then reduce the gap n = len(arr) - gap = int(n / 2) + gap = n // 2 # Do a gapped insertion sort for this gap size. # The first gap elements a[0..gap-1] are already in gapped diff --git a/data_structures/array/all_numbers_divisible.py b/data_structures/array/all_numbers_divisible.py index 26eaaabd..6fe6a82f 100644 --- a/data_structures/array/all_numbers_divisible.py +++ b/data_structures/array/all_numbers_divisible.py @@ -11,10 +11,7 @@ def check(arr): for i in arr: if i < min: min = i - for i in arr: - if not i % min == 0: - return False - return True + return all(i % min == 0 for i in arr) arr = [20,10,15,5,100,200, 201] diff --git a/data_structures/array/binary_search_infinite_array.py b/data_structures/array/binary_search_infinite_array.py index 6eff9207..ea865b92 100644 --- a/data_structures/array/binary_search_infinite_array.py +++ b/data_structures/array/binary_search_infinite_array.py @@ -13,11 +13,7 @@ def binary_search(arr, start, end, val): def search(arr, val): if len(arr) == 1: - if arr[0] == val: - return "Found" - else: - return "Not found" - + return "Found" if arr[0] == val else "Not found" temp = arr[0] low = 0 high = 1 @@ -29,10 +25,7 @@ def search(arr, val): ans = binary_search(arr, low, high, val) - if ans == -1: - return "Not Found" - else: - return "Found at index {}".format(ans) + return "Not Found" if ans == -1 else f"Found at index {ans}" arr = [1,3,5,6,7,8,9,11,13,15,19] diff --git a/data_structures/array/even_more_than_odd.py b/data_structures/array/even_more_than_odd.py index 62735d9c..3d6e8c74 100644 --- a/data_structures/array/even_more_than_odd.py +++ b/data_structures/array/even_more_than_odd.py @@ -6,9 +6,8 @@ def rearrange(arr): if i % 2 == 0: if arr[i] > arr[i-1]: arr[i-1], arr[i] = arr[i], arr[i-1] - else: - if arr[i] < arr[i-1]: - arr[i-1], arr[i] = arr[i], arr[i-1] + elif arr[i] < arr[i-1]: + arr[i-1], arr[i] = arr[i], arr[i-1] print(arr) diff --git a/data_structures/array/find_given_sum_in_array.py b/data_structures/array/find_given_sum_in_array.py index 0aacc5b4..a1d1ab2c 100644 --- a/data_structures/array/find_given_sum_in_array.py +++ b/data_structures/array/find_given_sum_in_array.py @@ -5,7 +5,7 @@ def find_sum(arr, s): curr_sum = arr[0] start = 0 n = len(arr) - 1 - + i = 1 while i <= n: @@ -15,7 +15,7 @@ def find_sum(arr, s): start += 1 if curr_sum == s: - return "Found between {} and {}".format(start, i - 1) + return f"Found between {start} and {i - 1}" curr_sum = curr_sum + arr[i] i += 1 diff --git a/data_structures/array/first_repeating_char.py b/data_structures/array/first_repeating_char.py index 89477411..196cb2ae 100644 --- a/data_structures/array/first_repeating_char.py +++ b/data_structures/array/first_repeating_char.py @@ -8,12 +8,11 @@ # Typically an integer has at-least 32 bits and we need to store presence/absence of only 26 characters. def first_recurrence(s): - checker = 0 - pos = 0 + checker = 0 for i in s: val = ord(i) - ord('a') if (checker & (1 << val) > 0): return i - checker = checker | (1 << val) - pos += 1 + else: + checker = checker | (1 << val) return -1 diff --git a/data_structures/array/min_product.py b/data_structures/array/min_product.py index 01bbfcb9..ed576f3d 100644 --- a/data_structures/array/min_product.py +++ b/data_structures/array/min_product.py @@ -44,7 +44,7 @@ def find(arr): if count_negative == 0: return min_pos - if count_negative & 1 == 0 and count_negative != 0: + if count_negative & 1 == 0: prod = int(prod / max_neg) return prod diff --git a/data_structures/array/min_swaps.py b/data_structures/array/min_swaps.py index 3fdd13a7..3e3d4bc5 100644 --- a/data_structures/array/min_swaps.py +++ b/data_structures/array/min_swaps.py @@ -1,22 +1,8 @@ # Minimum swaps required to bring all elements less than or equal to k together def min_swaps(arr, k): - # First find out how many elements are there which are less than or - # equal to k - count = 0 - for i in arr: - if i <= k: - count += 1 - - # This count defines a window - inside this window all our elements should - # be placed - # Find the count of bad elements - elements which are more than k and that will be - # our starting answer as we will have to swap them out - bad = 0 - for i in range(0, count): - if arr[i] > k: - bad += 1 - + count = sum(1 for i in arr if i <= k) + bad = sum(1 for i in range(0, count) if arr[i] > k) ans = bad j = count @@ -26,7 +12,7 @@ def min_swaps(arr, k): if arr[i] > k: bad -= 1 # because we have moved the bad element out of the window - + if arr[j] > k: bad += 1 diff --git a/data_structures/array/moves_zeros_to_end.py b/data_structures/array/moves_zeros_to_end.py index c5589961..0180313a 100644 --- a/data_structures/array/moves_zeros_to_end.py +++ b/data_structures/array/moves_zeros_to_end.py @@ -4,7 +4,7 @@ def move(arr): count = 0 for a in arr: - if not a == 0: + if a != 0: arr[count] = a count += 1 while count < len(nums): diff --git a/data_structures/array/partition_three_parts_equal_sum.py b/data_structures/array/partition_three_parts_equal_sum.py index ed3419d5..39d1838a 100644 --- a/data_structures/array/partition_three_parts_equal_sum.py +++ b/data_structures/array/partition_three_parts_equal_sum.py @@ -1,6 +1,6 @@ def partition(arr): s = sum(arr) - if not s % 3 == 0: + if s % 3 != 0: return False s = s / 3 targets = [2*s, s] @@ -12,5 +12,5 @@ def partition(arr): targets.pop() if not targets: return True - + return False diff --git a/data_structures/array/permutations_of_word.py b/data_structures/array/permutations_of_word.py index e5eb8998..25414245 100644 --- a/data_structures/array/permutations_of_word.py +++ b/data_structures/array/permutations_of_word.py @@ -7,8 +7,7 @@ def permutation(lst): for i in range(len(lst)): m = lst[i] rem_lst = lst[:i] + lst[i+1:] - for p in permutation(rem_lst): - l.append([m] + p) + l.extend([m] + p for p in permutation(rem_lst)) return l diff --git a/data_structures/array/quick_sort.py b/data_structures/array/quick_sort.py index ddc87147..065c928d 100644 --- a/data_structures/array/quick_sort.py +++ b/data_structures/array/quick_sort.py @@ -12,11 +12,10 @@ def quicksort(array): if len(array) < 2: return array - else: - pivot = array[0] - less = [i for i in array[1:] if i <= pivot] - greater = [i for i in array[1:] if i > pivot] - return quicksort(less) + [pivot] + quicksort(greater) + pivot = array[0] + less = [i for i in array[1:] if i <= pivot] + greater = [i for i in array[1:] if i > pivot] + return quicksort(less) + [pivot] + quicksort(greater) array = [100, 5, 72, 41, 80, 1, 99, 36, 27, 78] print(quicksort(array)) # [1, 5, 27, 36, 41, 72, 78, 80, 99, 100] diff --git a/data_structures/array/rotation.py b/data_structures/array/rotation.py index c89ab715..80b184d4 100644 --- a/data_structures/array/rotation.py +++ b/data_structures/array/rotation.py @@ -1,7 +1,5 @@ def gcd(a, b): - if b == 0: - return a - return gcd(b, a%b) + return a if b == 0 else gcd(b, a%b) def rotate(arr, d): diff --git a/data_structures/array/sorted_array_three_common_elements.py b/data_structures/array/sorted_array_three_common_elements.py index 413812c8..6eb6d52d 100644 --- a/data_structures/array/sorted_array_three_common_elements.py +++ b/data_structures/array/sorted_array_three_common_elements.py @@ -3,7 +3,7 @@ def common(arr1, arr2, arr3): i, j, k = 0, 0, 0 while i < len(arr1) and j < len(arr2) and k < len(arr3): - if arr1[i] == arr2[j] and arr2[j] == arr3[k]: + if arr1[i] == arr2[j] == arr3[k]: res.append(arr1[i]) i += 1 j += 1 diff --git a/data_structures/array/square_of_sorted_array.py b/data_structures/array/square_of_sorted_array.py index 1bebb758..18accd7e 100644 --- a/data_structures/array/square_of_sorted_array.py +++ b/data_structures/array/square_of_sorted_array.py @@ -1,15 +1,15 @@ def square(arr): n = len(arr) j = 0 - + # Counting the number of negative elements while j < n and arr[j] < 0: j += 1 - + i = j - 1 # index of last negative element ans = [] - while 0 <= i and j < n: + while i >= 0 and j < n: if arr[i] ** 2 < arr[j] ** 2: ans.append(arr[i] ** 2) i -= 1 @@ -20,7 +20,7 @@ def square(arr): while i >= 0: ans.append(arr[i] ** 2) i -= 1 - + while j < n: ans.append(arr[j] ** 2) j += 1 diff --git a/data_structures/array/transpose_matrix.py b/data_structures/array/transpose_matrix.py index c7abb7f4..76c57278 100644 --- a/data_structures/array/transpose_matrix.py +++ b/data_structures/array/transpose_matrix.py @@ -2,12 +2,8 @@ class Solution: def transpose(self, A: List[List[int]]) -> List[List[int]]: l=[] i=0 - while(i!=len(A[0])): - x=[] - j=0 - while(j k: - curr = curr.left - else: - curr = curr.right + curr = curr.left if curr.val > k else curr.right return element diff --git a/data_structures/bst/dfs_iterative.py b/data_structures/bst/dfs_iterative.py index 41f04481..3a71c37b 100644 --- a/data_structures/bst/dfs_iterative.py +++ b/data_structures/bst/dfs_iterative.py @@ -32,16 +32,14 @@ def postorder(root): if curr: stack.append(curr) curr = curr.left + elif temp := stack[-1].right: + curr = temp else: - temp = stack[-1].right - if not temp: + temp = stack.pop() + print(temp.val, end=" ") + while stack and temp == stack[-1].right: temp = stack.pop() print(temp.val, end=" ") - while stack and temp == stack[-1].right: - temp = stack.pop() - print(temp.val, end=" ") - else: - curr = temp def preorder(root): diff --git a/data_structures/bst/duplicate_keys.py b/data_structures/bst/duplicate_keys.py index a09dc2c1..ba1fe6b3 100644 --- a/data_structures/bst/duplicate_keys.py +++ b/data_structures/bst/duplicate_keys.py @@ -55,29 +55,28 @@ def min_value_node(root): def delete(root, val): if not root: return None - + if val < root.val: root.left = delete(root.left, val) elif val > root.val: root.right = delete(root.right, val) + elif root.count > 1: + root.count -= 1 else: - if root.count > 1: - root.count -= 1 - else: - # check if left node is None - if not root.left: - temp = root.right - root = None - return temp - # chec if right node is None - if not root.right: - temp = root.left - root = None - return temp - - temp = min_value_node(root.right) - root.val = temp.val - root.right = delete(root.right, temp.val) + # check if left node is None + if not root.left: + temp = root.right + root = None + return temp + # chec if right node is None + if not root.right: + temp = root.left + root = None + return temp + + temp = min_value_node(root.right) + root.val = temp.val + root.right = delete(root.right, temp.val) return root diff --git a/data_structures/bst/insertion_iterative.py b/data_structures/bst/insertion_iterative.py index f7d5b0a1..7e3c3b56 100644 --- a/data_structures/bst/insertion_iterative.py +++ b/data_structures/bst/insertion_iterative.py @@ -12,11 +12,7 @@ def insert(root, val): curr = root while curr: parent = curr - if curr.val <= val: - curr = curr.right - else: - curr = curr.left - + curr = curr.right if curr.val <= val else curr.left if parent.val <= val: parent.right = new_node else: diff --git a/data_structures/bst/insertion_recursive.py b/data_structures/bst/insertion_recursive.py index 51504613..3325000c 100644 --- a/data_structures/bst/insertion_recursive.py +++ b/data_structures/bst/insertion_recursive.py @@ -8,17 +8,15 @@ def __init__(self, val): def insertion_recursive(root, val): if not root: return Node(val) - else: - if root.val < val: - if root.right is None: - root.right = Node(val) - else: - insertion_recursive(root.right, val) + if root.val < val: + if root.right is None: + root.right = Node(val) else: - if root.left is None: - root.left = Node(val) - else: - insertion_recursive(root.left, val) + insertion_recursive(root.right, val) + elif root.left is None: + root.left = Node(val) + else: + insertion_recursive(root.left, val) def inorder(root): diff --git a/data_structures/bst/range_sum.py b/data_structures/bst/range_sum.py index 22305884..4d7f1450 100644 --- a/data_structures/bst/range_sum.py +++ b/data_structures/bst/range_sum.py @@ -10,8 +10,7 @@ def range_sum_preorder(root, L, R): stack = [root] sum = 0 while stack: - node = stack.pop() - if node: + if node := stack.pop(): if L <= node.val <= R: sum += node.val if L < node.val: diff --git a/data_structures/bst/search.py b/data_structures/bst/search.py index 4ff5aebb..fa822ce1 100644 --- a/data_structures/bst/search.py +++ b/data_structures/bst/search.py @@ -8,10 +8,7 @@ def __init__(self, val): def search(root, val): if root is None or root.val == val: return root - if root.val < val: - return search(root.left, val) - else: - return search(root.right, val) + return search(root.left, val) if root.val < val else search(root.right, val) def search_iterative(root, val): diff --git a/data_structures/bst/second_largest_in_bst.py b/data_structures/bst/second_largest_in_bst.py index 334a3dd6..c33ad961 100644 --- a/data_structures/bst/second_largest_in_bst.py +++ b/data_structures/bst/second_largest_in_bst.py @@ -42,7 +42,7 @@ def second_largest(root): def insert(root, key): - if root == None: + if root is None: return Node(key) if key < root.val: root.left = insert(root.left, key) diff --git a/data_structures/circular_linked_list/check_circular_linked_list.py b/data_structures/circular_linked_list/check_circular_linked_list.py index 4da76507..e747371c 100644 --- a/data_structures/circular_linked_list/check_circular_linked_list.py +++ b/data_structures/circular_linked_list/check_circular_linked_list.py @@ -16,7 +16,7 @@ def check(head): while curr: if curr.next == head: return True - elif curr.next == None: + elif curr.next is None: return False curr = curr.next diff --git a/data_structures/circular_linked_list/delete.py b/data_structures/circular_linked_list/delete.py index ebbedcd2..d01e431f 100644 --- a/data_structures/circular_linked_list/delete.py +++ b/data_structures/circular_linked_list/delete.py @@ -5,9 +5,9 @@ def __init__(self, val): self.next = None def delete(head, val): - if head == None: + if head is None: return "List is empty" - + curr = head prev = None diff --git a/data_structures/deque/deque.py b/data_structures/deque/deque.py index d578c8e2..42aebeae 100644 --- a/data_structures/deque/deque.py +++ b/data_structures/deque/deque.py @@ -1,42 +1,29 @@ class Deque(): def __init__(self): - self.data = list() + self.data = [] def push_front(self, elem): - temp = list() - temp.append(elem) - - for i in self.data: - temp.append(i) - + temp = [elem] + temp.extend(iter(self.data)) self.data = temp def push_back(self, elem): self.data.append(elem) def pop_front(self): - temp = list() - - for i in range(0, len(self.data)): - if not i==0: - temp.append(self.data[i]) - + temp = [self.data[i] for i in range(0, len(self.data)) if i != 0] self.data = temp def pop_back(self): - temp = list() - - for i in range(0, len(self.data)): - if not i==len(self.data)-1: - temp.append(self.data[i]) - + temp = [ + self.data[i] + for i in range(0, len(self.data)) + if i != len(self.data) - 1 + ] self.data = temp def get_first(self): - if(len(self.data)>0): - return self.data[0] - else: - return "Deque is empty" + return self.data[0] if (len(self.data)>0) else "Deque is empty" def get_last(self): if(len(self.data)>0): @@ -48,21 +35,11 @@ def size(self): return len(self.data) def isEmpty(self): - if len(self.data) == 0: - return True - return False + return len(self.data) == 0 def contains(self, elem): - for i in self.data: - if i==elem: - return True - - return False + return any(i==elem for i in self.data) def printElems(self): - result = "" - - for i in self.data: - result += str(i) + " | " - + result = "".join(f"{str(i)} | " for i in self.data) print(result) \ No newline at end of file diff --git a/data_structures/doubly_linked_list/doubly_linked_list.py b/data_structures/doubly_linked_list/doubly_linked_list.py index 9feb64b0..e37c74bc 100644 --- a/data_structures/doubly_linked_list/doubly_linked_list.py +++ b/data_structures/doubly_linked_list/doubly_linked_list.py @@ -15,15 +15,12 @@ def empty(self): def search(self, data): if self.empty(): return None - + auxiliar = self.first.next while auxiliar.next != None and auxiliar.data != data: auxiliar = auxiliar.next - if auxiliar.data == data: - return auxiliar.data - - return None + return auxiliar.data if auxiliar.data == data else None def append(self, data): self.last.next = Node(data = data, next = None, previous = self.last) @@ -37,13 +34,13 @@ def __str__(self): aux = self.first format_ = "" - + while aux.next != None: if aux.data!= None: - format_ += str(aux.data) + " " + format_ += f"{str(aux.data)} " aux = aux.next - format_ += str(aux.data) + "" - + format_ += f"{str(aux.data)}" + return format_ def remove(self, data): @@ -54,17 +51,17 @@ def remove(self, data): while auxiliar != None and auxiliar.data != data: auxiliar = auxiliar.next - if auxiliar == None: return None - else: - item = auxiliar.data + if auxiliar is None: + if auxiliar == None: return None + item = auxiliar.data - if auxiliar.previous != None: - auxiliar.previous.next = auxiliar.next - if auxiliar.next != None: - auxiliar.next.previous = auxiliar.previous + if auxiliar.previous != None: + auxiliar.previous.next = auxiliar.next + if auxiliar.next != None: + auxiliar.next.previous = auxiliar.previous if self.empty(): self.last = self.first = Node() - elif auxiliar.next == None: self.last = auxiliar.previous + elif auxiliar.next is None: self.last = auxiliar.previous del auxiliar return item diff --git a/data_structures/graphs/adjacency_list.py b/data_structures/graphs/adjacency_list.py index 6fe60466..32d49604 100644 --- a/data_structures/graphs/adjacency_list.py +++ b/data_structures/graphs/adjacency_list.py @@ -27,10 +27,10 @@ def add_edge(self, src, dest): def print_graph(self): for i in range(self.V): - print("Adjacency list of vertex {}\n head".format(i), end="") + print(f"Adjacency list of vertex {i}\n head", end="") temp = self.graph[i] while temp: - print(" -> {}".format(temp.vertex), end="") + print(f" -> {temp.vertex}", end="") temp = temp.next print(" \n") diff --git a/data_structures/graphs/adjacency_matrix.py b/data_structures/graphs/adjacency_matrix.py index f173bc37..92a30656 100644 --- a/data_structures/graphs/adjacency_matrix.py +++ b/data_structures/graphs/adjacency_matrix.py @@ -4,23 +4,19 @@ def __init__(self, vertices, directed: bool): self.V = vertices self.e = 0 self.d = directed - self.graph = [[0 for i in range(vertices)] for j in range(vertices)] + self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)] def add_edge(self, ver1, ver2): - if self.d: - self.graph[ver1][ver2] = 1 - else: - self.graph[ver1][ver2] = 1 + self.graph[ver1][ver2] = 1 + if not self.d: self.graph[ver2][ver1] = 1 def remove_edge(self, ver1, ver2): if self.graph[ver1][ver2] == 0: print("No edge between %d and %d" % (ver1, ver2)) return - if self.d: - self.graph[ver1][ver2] = 0 - else: - self.graph[ver1][ver2] = 0 + self.graph[ver1][ver2] = 0 + if not self.d: self.graph[ver2][ver1] = 0 def print_graph(self): diff --git a/data_structures/graphs/all_paths_between_two_vertices.py b/data_structures/graphs/all_paths_between_two_vertices.py index 3632d36e..b500f530 100644 --- a/data_structures/graphs/all_paths_between_two_vertices.py +++ b/data_structures/graphs/all_paths_between_two_vertices.py @@ -7,7 +7,7 @@ class Graph: def __init__(self, vertices): self.vertices = vertices - self.graph = [[] for i in range(vertices)] + self.graph = [[] for _ in range(vertices)] def add_edge(self, u, v): diff --git a/data_structures/graphs/bellman_ford.py b/data_structures/graphs/bellman_ford.py index 49aabe8a..67c3822a 100644 --- a/data_structures/graphs/bellman_ford.py +++ b/data_structures/graphs/bellman_ford.py @@ -55,8 +55,7 @@ def bellman_ford(self, source, destination): parent[source] = source distance[source] = source - for i in range(self.vertices - 1): # Doing V - 1 times to find shortest distance - + for _ in range(self.vertices - 1): for (u, v) in self.edges: wt = self.edges[(u, v)].weight @@ -67,7 +66,7 @@ def bellman_ford(self, source, destination): # Now for the Vth iteration, check for the negative cycle negative_cycle_present = False - + for (u, v) in self.edges: wt = self.edges[(u, v)].weight if distance[v] > distance[u] + wt: diff --git a/data_structures/graphs/bfs.py b/data_structures/graphs/bfs.py index 67722def..a5611685 100644 --- a/data_structures/graphs/bfs.py +++ b/data_structures/graphs/bfs.py @@ -14,9 +14,8 @@ def add_edge(self, u, v): def bfs(self, s): visited = [False] * self.vertices - queue = [] + queue = [s] - queue.append(s) visited[s] = True bfs = [] diff --git a/data_structures/graphs/bipartite_graph.py b/data_structures/graphs/bipartite_graph.py index 0296de6e..2c863b88 100644 --- a/data_structures/graphs/bipartite_graph.py +++ b/data_structures/graphs/bipartite_graph.py @@ -31,8 +31,7 @@ def add_edge(self, u, v): def bfs(self, s): visited = [False] * self.V - queue = [] - queue.append(s) + queue = [s] visited[s] = True while queue: @@ -53,15 +52,13 @@ def is_bipartite(self, s): colors = [-1] * self.V colors[s] = 1 # Color soure vertex red - queue = [] - queue.append(s) - + queue = [s] while queue: s = queue.pop(0) if s in self.graph[s]: # Check for self loop return False - + # An edge u to v exists and destination is not # colored for i in self.graph[s]: diff --git a/data_structures/graphs/check_if_graph_is_tree.py b/data_structures/graphs/check_if_graph_is_tree.py index 90ed3425..d80eb527 100644 --- a/data_structures/graphs/check_if_graph_is_tree.py +++ b/data_structures/graphs/check_if_graph_is_tree.py @@ -24,12 +24,9 @@ def add_edge(self, u, v): def is_tree(self, s): visited = [False] * self.vertices parent = [-1] * self.vertices - stack = [] - visited[s] = True no_of_visited = 1 - stack.append(s) - + stack = [s] while stack: s = stack.pop() @@ -42,10 +39,7 @@ def is_tree(self, s): elif parent[s] != i: return "Not a tree" - if no_of_visited == self.vertices: - return "Graph is Tree" - else: - return "Not a tree" + return "Graph is Tree" if no_of_visited == self.vertices else "Not a tree" g = Graph(7) diff --git a/data_structures/graphs/count_edges.py b/data_structures/graphs/count_edges.py index 6b9d1f87..56d22834 100644 --- a/data_structures/graphs/count_edges.py +++ b/data_structures/graphs/count_edges.py @@ -12,7 +12,7 @@ class Graph: def __init__(self, vertices): self.V = vertices - self.graph = [[] for i in range(vertices)] + self.graph = [[] for _ in range(vertices)] def add_edge(self, u, v): @@ -21,11 +21,7 @@ def add_edge(self, u, v): def count_edges(self): - s = 0 - - for i in range(self.V): - s += len(self.graph[i]) - + s = sum(len(self.graph[i]) for i in range(self.V)) return s // 2 diff --git a/data_structures/graphs/count_trees.py b/data_structures/graphs/count_trees.py index 28033ee9..7d1062ce 100644 --- a/data_structures/graphs/count_trees.py +++ b/data_structures/graphs/count_trees.py @@ -27,10 +27,9 @@ def count_trees(self): for s in range(self.vertices): if not visited[s]: visited[s] = True - stack = [] - stack.append(s) + stack = [s] count += 1 - + while stack: print(stack) s = stack.pop() @@ -39,7 +38,7 @@ def count_trees(self): if not visited[i]: visited[i] = True stack.append(i) - + return count diff --git a/data_structures/graphs/cycle_in_directed_graph.py b/data_structures/graphs/cycle_in_directed_graph.py index 2a2b3253..bd3821e6 100644 --- a/data_structures/graphs/cycle_in_directed_graph.py +++ b/data_structures/graphs/cycle_in_directed_graph.py @@ -17,11 +17,12 @@ def is_cyclic_util(self, v, visited, rec_stack): rec_stack[v] = True for neighbour in self.graph[v]: - if visited[neighbour] == False: - if self.is_cyclic_util(neighbour, visited, rec_stack): - return True - - elif rec_stack[neighbour] == True: + if ( + visited[neighbour] == False + and self.is_cyclic_util(neighbour, visited, rec_stack) + or visited[neighbour] != False + and rec_stack[neighbour] == True + ): return True rec_stack[v] = False diff --git a/data_structures/graphs/cycle_in_undirected_graph.py b/data_structures/graphs/cycle_in_undirected_graph.py index bb16b122..a51a852e 100644 --- a/data_structures/graphs/cycle_in_undirected_graph.py +++ b/data_structures/graphs/cycle_in_undirected_graph.py @@ -15,15 +15,13 @@ def add_edge(self, u, v): def is_cyclic_util(self, v, visited, parent): visited[v] = True - for i in self.graph[v]: - if visited[i] == False: - if self.is_cyclic_util(i, visited, v): - return True - - elif parent != i: - return True - - return False + return any( + visited[i] == False + and self.is_cyclic_util(i, visited, v) + or visited[i] != False + and parent != i + for i in self.graph[v] + ) def is_cyclic(self): diff --git a/data_structures/graphs/cycle_in_undirected_graph_union_find.py b/data_structures/graphs/cycle_in_undirected_graph_union_find.py index e8e0af42..8398840a 100644 --- a/data_structures/graphs/cycle_in_undirected_graph_union_find.py +++ b/data_structures/graphs/cycle_in_undirected_graph_union_find.py @@ -24,10 +24,7 @@ def union(self, parent, x, y): def find_parent(self, parent, i): - if parent[i] == -1: - return i - else: - return self.find_parent(parent, parent[i]) + return i if parent[i] == -1 else self.find_parent(parent, parent[i]) def check_cyclic(self): diff --git a/data_structures/graphs/dag_longest_path.py b/data_structures/graphs/dag_longest_path.py index 796c43da..82daf171 100644 --- a/data_structures/graphs/dag_longest_path.py +++ b/data_structures/graphs/dag_longest_path.py @@ -47,9 +47,7 @@ def longest_path(self, s): i = stack.pop(0) for vertex, weight in self.graph[i]: - if distance[vertex] < distance[i] + weight: - distance[vertex] = distance[i] + weight - + distance[vertex] = max(distance[vertex], distance[i] + weight) for i in range(self.vertices): print(f"{s} -> {i} = {distance[i]}") diff --git a/data_structures/graphs/dag_shortest_path.py b/data_structures/graphs/dag_shortest_path.py index 36bebda4..0b29b7de 100644 --- a/data_structures/graphs/dag_shortest_path.py +++ b/data_structures/graphs/dag_shortest_path.py @@ -56,9 +56,7 @@ def shortest_path(self, s): i = stack.pop(0) for vertex, weight in self.graph[i]: - if distance[vertex] > distance[i] + weight: - distance[vertex] = distance[i] + weight - + distance[vertex] = min(distance[vertex], distance[i] + weight) for i in range(self.vertices): print(f"{s} -> {i} = {distance[i]}") diff --git a/data_structures/graphs/level_of_nodes.py b/data_structures/graphs/level_of_nodes.py index c453fa95..7481fec7 100644 --- a/data_structures/graphs/level_of_nodes.py +++ b/data_structures/graphs/level_of_nodes.py @@ -22,17 +22,15 @@ def add_edge(self, u, v): def print_levels(self, s): levels = [None] * self.vertices levels[s] = 0 - queue = [] - queue.append(s) - + queue = [s] while queue: s = queue.pop(0) for i in self.graph[s]: - if levels[i] == None: + if levels[i] is None: levels[i] = levels[s] + 1 queue.append(i) - + print('Node \t Level') for node, level in enumerate(levels): print(f'{node} \t {level}') diff --git a/data_structures/graphs/max_edges_to_make_bipartite.py b/data_structures/graphs/max_edges_to_make_bipartite.py index 9b42fb82..749d370c 100644 --- a/data_structures/graphs/max_edges_to_make_bipartite.py +++ b/data_structures/graphs/max_edges_to_make_bipartite.py @@ -26,15 +26,10 @@ def add_edge(self, u, v): def bfs(self, s): count_color0 = 0 - count_color1 = 0 - colors = [-1] * self.vertices colors[s] = 1 - count_color1 += 1 - - queue = [] - queue.append(s) - + count_color1 = 0 + 1 + queue = [s] while queue: s = queue.pop(0) @@ -46,9 +41,9 @@ def bfs(self, s): else: count_color1 += 1 queue.append(i) - - ans = (count_color0 * count_color1) - (self.vertices - 1) - return ans if ans > 0 else 0 + + ans = (count_color0 * count_color1) - (self.vertices - 1) + return max(ans, 0) g = Graph(5) diff --git a/data_structures/graphs/min_edges_between_two_vertices.py b/data_structures/graphs/min_edges_between_two_vertices.py index 13456d5f..2a8e8667 100644 --- a/data_structures/graphs/min_edges_between_two_vertices.py +++ b/data_structures/graphs/min_edges_between_two_vertices.py @@ -16,9 +16,8 @@ def add_edge(self, u, v): def find_min_edges(self, u, v): visited = [False] * self.vertices distance = [0] * self.vertices - queue = [] + queue = [u] - queue.append(u) visited[u] = True while queue: diff --git a/data_structures/graphs/min_number_of_operations.py b/data_structures/graphs/min_number_of_operations.py index 7d783e30..0399d687 100644 --- a/data_structures/graphs/min_number_of_operations.py +++ b/data_structures/graphs/min_number_of_operations.py @@ -23,9 +23,7 @@ def min_steps(x, y): node_x = Node(x, 0) visited = [] - queue = [] - queue.append(node_x) - + queue = [node_x] while queue: s = queue.pop(0) @@ -42,7 +40,7 @@ def min_steps(x, y): if s.value * 2 not in visited: new_node = Node(s.value * 2, s.level + 1) queue.append(new_node) - + if s.value - 1 not in visited: new_node = Node(s.value - 1, s.level + 1) queue.append(new_node) diff --git a/data_structures/graphs/mother_vertex.py b/data_structures/graphs/mother_vertex.py index 794c88ee..30eeb435 100644 --- a/data_structures/graphs/mother_vertex.py +++ b/data_structures/graphs/mother_vertex.py @@ -45,11 +45,7 @@ def find_mother(self): visited = [False] * self.V self.dfs_util(v, visited) - if any(i == False for i in visited): - return -1 - - else: - return v + return -1 if any(i == False for i in visited) else v g = Graph(7) diff --git a/data_structures/graphs/not_reachable_nodes.py b/data_structures/graphs/not_reachable_nodes.py index df2e765a..e00118d3 100644 --- a/data_structures/graphs/not_reachable_nodes.py +++ b/data_structures/graphs/not_reachable_nodes.py @@ -25,13 +25,7 @@ def count_nodes(self, v): self.dfs_util(v, visited) - count = 0 - - for i in range(self.V): - if visited[i] == False: - count += 1 - - return count + return sum(1 for i in range(self.V) if visited[i] == False) g = Graph(8) g.add_edge(0, 1) diff --git a/data_structures/graphs/number_of_triangles.py b/data_structures/graphs/number_of_triangles.py index aa0a1669..f5d78e05 100644 --- a/data_structures/graphs/number_of_triangles.py +++ b/data_structures/graphs/number_of_triangles.py @@ -8,7 +8,7 @@ class Graph: def __init__(self, vertices, is_directed): self.V = vertices - self.graph = [[] for i in range(vertices)] + self.graph = [[] for _ in range(vertices)] self.is_directed = is_directed diff --git a/data_structures/graphs/root_which_gives_min_height.py b/data_structures/graphs/root_which_gives_min_height.py index 7a079196..4aab8e41 100644 --- a/data_structures/graphs/root_which_gives_min_height.py +++ b/data_structures/graphs/root_which_gives_min_height.py @@ -27,10 +27,10 @@ def root_min_height(self): for i in range(self.V): if self.degree[i] == 1: # To identify leaf nodes q.put(i) - + # now move inwards from the leaf node while self.V > 2: - for i in range(q.qsize()): + for _ in range(q.qsize()): t = q.get() self.V -= 1 @@ -41,7 +41,7 @@ def root_min_height(self): if self.degree[j] == 1: q.put(j) - res = list() + res = [] while q.qsize() > 0: res.append(q.get()) diff --git a/data_structures/graphs/same_path.py b/data_structures/graphs/same_path.py index 82219691..affe6753 100644 --- a/data_structures/graphs/same_path.py +++ b/data_structures/graphs/same_path.py @@ -29,14 +29,12 @@ def dfs(self): outtime = [0] * self.vertices timer = 0 num_children_visited = [0] * self.vertices - + for s in range(self.vertices): if not visited[s]: visited[s] = True - stack = [] - stack.append(s) - + stack = [s] while stack: s = stack.pop() timer += 1 @@ -51,7 +49,7 @@ def dfs(self): if num_children_visited[i] == len(self.graph[i]): timer += 1 outtime[i] = timer - + print('intime - ', intime) print('outtime - ', outtime) print('num_children_visited - ', num_children_visited) @@ -60,10 +58,11 @@ def dfs(self): def check_same_path(self, u, v): - if (self.intime[u] < self.intime[v] and self.outtime[u] > self.outtime[v]) or \ - (self.intime[v] < self.intime[u] and self.outtime[v] > self.outtime[u]): - return True - return False + return ( + self.intime[u] < self.intime[v] and self.outtime[u] > self.outtime[v] + ) or ( + self.intime[v] < self.intime[u] and self.outtime[v] > self.outtime[u] + ) g = Graph(7) diff --git a/data_structures/graphs/same_path_recursive.py b/data_structures/graphs/same_path_recursive.py index 3b2087aa..4459df66 100644 --- a/data_structures/graphs/same_path_recursive.py +++ b/data_structures/graphs/same_path_recursive.py @@ -43,11 +43,10 @@ def on_same_path(self, u, v): if visited[vertex] == False: self.dfs(vertex, intime, outtime, timer, visited) - - if (intime[u] < intime[v] and outtime[u] > outtime[v]) \ - or (intime[v] < intime[u] and outtime[v] > outtime[u]): - return True - return False + + return (intime[u] < intime[v] and outtime[u] > outtime[v]) or ( + intime[v] < intime[u] and outtime[v] > outtime[u] + ) g = Graph(9) diff --git a/data_structures/graphs/shortest_path_unweighted_graph.py b/data_structures/graphs/shortest_path_unweighted_graph.py index ca5cd60b..c5f5fbb8 100644 --- a/data_structures/graphs/shortest_path_unweighted_graph.py +++ b/data_structures/graphs/shortest_path_unweighted_graph.py @@ -27,9 +27,7 @@ def bfs(self, s): parent = [-1] * self.vertices visited = [False] * self.vertices visited[s] = True - queue = [] - queue.append(s) - + queue = [s] while queue: s = queue.pop(0) @@ -38,7 +36,7 @@ def bfs(self, s): queue.append(i) parent[i] = s visited[i] = True - + return parent diff --git a/data_structures/graphs/tree_stays_bipartite.py b/data_structures/graphs/tree_stays_bipartite.py index cda2299a..a1146234 100644 --- a/data_structures/graphs/tree_stays_bipartite.py +++ b/data_structures/graphs/tree_stays_bipartite.py @@ -11,7 +11,7 @@ class Graph: def __init__(self, vertices): self.vertices = vertices - self.graph = [[] for i in range(vertices)] + self.graph = [[] for _ in range(vertices)] def add_edge(self, u, v): @@ -25,14 +25,13 @@ def bfs(self, s): colors = [-1] * self.vertices colors[s] = 1 - queue = [] + queue = [s] - queue.append(s) visited[s] = True while queue: u = queue.pop(0) - + for v in self.graph[u]: if colors[v] == -1: # This is a tree. So not visited and not colored is same as there is no cycle colors[v] = 1 - colors[u] @@ -40,10 +39,7 @@ def bfs(self, s): color_count[colors[v]] += 1 visited[v] = True - # Counting the max number of edges for graph - graph_edges = color_count[0] * color_count[1] - - return graph_edges + return color_count[0] * color_count[1] # Number of tree nodes diff --git a/data_structures/heap/kth_largest_element_in_stream.py b/data_structures/heap/kth_largest_element_in_stream.py index dfc278e4..93abd3db 100644 --- a/data_structures/heap/kth_largest_element_in_stream.py +++ b/data_structures/heap/kth_largest_element_in_stream.py @@ -35,11 +35,10 @@ def insert(self, x): if len(self.heap) < self.k: # when the heap is empty or size is less than K heappush(self.heap, x) self.curr_min = self.heap[0] - else: - if x > self.curr_min: - heappop(self.heap) # remove the curr min element - heappush(self.heap, x) # insert x - self.curr_min = self.heap[0] + elif x > self.curr_min: + heappop(self.heap) # remove the curr min element + heappush(self.heap, x) # insert x + self.curr_min = self.heap[0] def find_kth_max(self): diff --git a/data_structures/heap/max_heap.py b/data_structures/heap/max_heap.py index 29fcef70..4bf8cff9 100644 --- a/data_structures/heap/max_heap.py +++ b/data_structures/heap/max_heap.py @@ -41,15 +41,11 @@ def is_leaf(self, pos): index of children are twice their index as those indexes do not exist in the heap """ - if self.mid_index() <= pos <= self.last_index(): - return True - return False + return self.mid_index() <= pos <= self.last_index() def is_empty(self): - if self.size == 0: - return True - return False + return self.size == 0 def insert(self, value): @@ -80,20 +76,21 @@ def max_heapify(self, pos): This function will run whenever a node is non-leaf node and smaller than its childen """ - if not self.is_leaf(pos): - left = self.heap[self.left_child(pos)] - right = self.heap[self.right_child(pos)] - curr = self.heap[pos] - - if curr < left or curr < right: - - # This check is only to prevent out-of-index error - if left > right: - self.swap(pos, self.left_child(pos)) - self.max_heapify(self.left_child(pos)) - else: - self.swap(pos, self.right_child(pos)) - self.max_heapify(self.right_child(pos)) + if self.is_leaf(pos): + return + left = self.heap[self.left_child(pos)] + right = self.heap[self.right_child(pos)] + curr = self.heap[pos] + + if curr < left or curr < right: + + # This check is only to prevent out-of-index error + if left > right: + self.swap(pos, self.left_child(pos)) + self.max_heapify(self.left_child(pos)) + else: + self.swap(pos, self.right_child(pos)) + self.max_heapify(self.right_child(pos)) def swap(self, x, y): diff --git a/data_structures/heap/median_of_infinite_stream.py b/data_structures/heap/median_of_infinite_stream.py index 9ce834a8..818c004e 100644 --- a/data_structures/heap/median_of_infinite_stream.py +++ b/data_structures/heap/median_of_infinite_stream.py @@ -54,10 +54,9 @@ def add_number(self, num): max_popped = -1 * heappop(self.max_heap) heappush(self.min_heap, max_popped) heappush(self.max_heap, -1 * num) - self.find_median('avg') else: heappush(self.min_heap, num) - self.find_median('avg') + self.find_median('avg') else: if num > self.curr_median: # num will go to the min heap and the min element @@ -65,12 +64,11 @@ def add_number(self, num): min_popped = heappop(self.min_heap) heappush(self.max_heap, -1 * min_popped) heappush(self.min_heap, num) - self.find_median('max') - else: # num will go to the max heap heappush(self.max_heap, -1 * num) - self.find_median('max') + + self.find_median('max') def find_median(self, how): diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index 069524d4..be1d0e82 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -17,9 +17,7 @@ def is_empty(self): def is_leaf(self, pos): - if self.mid_index() <= pos <= self.last_index(): - return True - return False + return self.mid_index() <= pos <= self.last_index() def parent(self, pos): @@ -56,19 +54,20 @@ def pop_min(self): def min_heapify(self, pos): - if not self.is_leaf(pos): - left = self.heap[self.left_child(pos)] - right = self.heap[self.right_child(pos)] - curr = self.heap[pos] - - if curr > left or curr > right: - - if left > right: - self.swap(pos, self.left_child(pos)) - self.min_heapify(self.left_child(pos)) - else: - self.swap(pos, self.right_child(pos)) - self.min_heapify(self.right_child(pos)) + if self.is_leaf(pos): + return + left = self.heap[self.left_child(pos)] + right = self.heap[self.right_child(pos)] + curr = self.heap[pos] + + if curr > left or curr > right: + + if left > right: + self.swap(pos, self.left_child(pos)) + self.min_heapify(self.left_child(pos)) + else: + self.swap(pos, self.right_child(pos)) + self.min_heapify(self.right_child(pos)) def insert(self, element): diff --git a/data_structures/heap/sum_elements_range.py b/data_structures/heap/sum_elements_range.py index 4a3b6645..7e144a1c 100644 --- a/data_structures/heap/sum_elements_range.py +++ b/data_structures/heap/sum_elements_range.py @@ -2,6 +2,7 @@ Find the sum of elements between k1th and k2th smallest elements """ + from heapq import heappush, heapify, heappop heap = [20, 8, 22, 4, 12, 10, 14] @@ -12,13 +13,8 @@ # extracting min k1 times -for i in range(k1): +for _ in range(k1): heappop(heap) -# now do extract min k2 - (k1 + 1) times -s = 0 - -for i in range(k2 - k1 - 1): - s += heappop(heap) - +s = sum(heappop(heap) for _ in range(k2 - k1 - 1)) print(s) diff --git a/data_structures/linked_list/cycle_detection.py b/data_structures/linked_list/cycle_detection.py index 5f697894..bbd596d4 100644 --- a/data_structures/linked_list/cycle_detection.py +++ b/data_structures/linked_list/cycle_detection.py @@ -13,7 +13,7 @@ def detect_cycle(head): fast = head.next while slow != fast: - if fast == None or fast.next == None: + if fast is None or fast.next is None: return False slow = slow.next fast = fast.next.next diff --git a/data_structures/linked_list/pair_swap.py b/data_structures/linked_list/pair_swap.py index 6388975c..3015c95d 100644 --- a/data_structures/linked_list/pair_swap.py +++ b/data_structures/linked_list/pair_swap.py @@ -6,7 +6,7 @@ def __init__(self, val): def pair_swap(head): - if head == None or head.next == None: + if head is None or head.next is None: return head root = head.next curr = head diff --git a/data_structures/linked_list/remove_duplicates.py b/data_structures/linked_list/remove_duplicates.py index ec3e3161..94d9d03a 100644 --- a/data_structures/linked_list/remove_duplicates.py +++ b/data_structures/linked_list/remove_duplicates.py @@ -5,7 +5,7 @@ def __init__(self, val): self.next = None def __str__(self): - return "{}".format(self.val) + return f"{self.val}" def remove_duplicates(head): diff --git a/data_structures/linked_list/remove_nth_node_from_end.py b/data_structures/linked_list/remove_nth_node_from_end.py index 4c30f038..3203d60e 100644 --- a/data_structures/linked_list/remove_nth_node_from_end.py +++ b/data_structures/linked_list/remove_nth_node_from_end.py @@ -10,7 +10,7 @@ def remove(head, n): slow = head fast = head - for i in range(n+1): + for _ in range(n+1): fast = fast.next while fast: fast = fast.next diff --git a/data_structures/palindromic_tree/palindromic_tree.py b/data_structures/palindromic_tree/palindromic_tree.py index 47992793..d1318806 100644 --- a/data_structures/palindromic_tree/palindromic_tree.py +++ b/data_structures/palindromic_tree/palindromic_tree.py @@ -42,13 +42,12 @@ def add_letter(self, string, index): if new_node.length == 1: new_node.suffix = self.null_root - self.previous = new_node else: self.previous = self.previous.suffix while index - 1 - self.previous.length < 0 or string[index - 1 - self.previous.length] != string[index]: self.previous = self.previous.suffix new_node.suffix = self.previous.next[string[index]] - self.previous = new_node + self.previous = new_node self.all_palindromes.append(new_node) def how_many_palindromes(self): diff --git a/data_structures/queue/queue.py b/data_structures/queue/queue.py index a02ae3ab..0cb65b08 100644 --- a/data_structures/queue/queue.py +++ b/data_structures/queue/queue.py @@ -25,7 +25,7 @@ def get(self): return de_queued def rotate(self, rotation): - for i in range(rotation): + for _ in range(rotation): self.put(self.get()) def size(self): diff --git a/data_structures/stack/balanced_expression.py b/data_structures/stack/balanced_expression.py index 60e3c506..06403223 100644 --- a/data_structures/stack/balanced_expression.py +++ b/data_structures/stack/balanced_expression.py @@ -1,26 +1,26 @@ stack = [] def checkBalanced(expr): for i in expr: - if i == "{" or i == "[" or i == "(": + if i in ["{", "[", "("]: stack.append(i) - elif i == "}" or i == "]" or i == ")": + elif i in ["}", "]", ")"]: if not stack: return False top = stack.pop() - if i == "}" and top != "{": - return False - elif i == "]" and top != "[": - return False - elif i == ")" and top != "(": + if ( + i == "}" + and top != "{" + or i == "]" + and top != "[" + or i == ")" + and top != "(" + ): return False else: print("Invalid Expression") return False - if not len(stack): - return True - else: - return False + return not len(stack) # main function expr = input() diff --git a/data_structures/stack/largest_rectangle_area_in_histogram.py b/data_structures/stack/largest_rectangle_area_in_histogram.py index 6aa55947..10b3bbfc 100644 --- a/data_structures/stack/largest_rectangle_area_in_histogram.py +++ b/data_structures/stack/largest_rectangle_area_in_histogram.py @@ -6,14 +6,14 @@ def max_area_histogram(histogram): - stack = list() - + stack = [] + max_area = 0 # Initialize max area index = 0 while index < len(histogram): - + if (not stack) or (histogram[stack[-1]] <= histogram[index]): stack.append(index) index += 1 @@ -21,13 +21,13 @@ def max_area_histogram(histogram): top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] - 1) if stack else index)) max_area = max(max_area, area) - + while stack: top_of_stack = stack.pop() area = (histogram[top_of_stack] * ((index - stack[-1] - 1) if stack else index)) - + max_area = max(max_area, area) - + return max_area diff --git a/data_structures/stack/stack_using_linked_list.py b/data_structures/stack/stack_using_linked_list.py index 794541b5..bf5868ce 100644 --- a/data_structures/stack/stack_using_linked_list.py +++ b/data_structures/stack/stack_using_linked_list.py @@ -27,12 +27,8 @@ def insert_first(self, new_element): def delete_first(self): "Delete the first (head) element in the LinkedList and return it" - current = self.head - if current: - if current.next: - self.head = current.next - else: - self.head = None + if current := self.head: + self.head = current.next if current.next else None return current else: return None diff --git a/data_structures/strings/KMP_Pattern_Search.py b/data_structures/strings/KMP_Pattern_Search.py index 37bfcd2c..5e81aaa2 100644 --- a/data_structures/strings/KMP_Pattern_Search.py +++ b/data_structures/strings/KMP_Pattern_Search.py @@ -22,10 +22,9 @@ def KMP_pattern_search(pattern, text): j += 1 if j == P: - print("Pattern found at index " + str(i-j)) + print(f"Pattern found at index {str(i - j)}") j=long_prefix_suffix[j-1] - # mismatch after j matches elif i < Q and pattern[j] != text[i]: if j != 0: j=long_prefix_suffix[j-1] @@ -44,12 +43,12 @@ def long_Prefix_Suffix_Array(pattern, P, long_prefix_suffix): l += 1 long_prefix_suffix[i] = l i += 1 + elif l == 0: + long_prefix_suffix[i] = 0 + i += 1 + else: - if l != 0: - l=long_prefix_suffix[l-1] - else: - long_prefix_suffix[i] = 0 - i += 1 + l=long_prefix_suffix[l-1] text = "ABABDABACDABABCABAB" pattern = "ABABCABAB" diff --git a/data_structures/strings/adjacent_vowel_pairs.py b/data_structures/strings/adjacent_vowel_pairs.py index e028b46c..db84a085 100644 --- a/data_structures/strings/adjacent_vowel_pairs.py +++ b/data_structures/strings/adjacent_vowel_pairs.py @@ -12,21 +12,18 @@ #function to check whether a character is vowel or not def is_vowel(character): - if character.lower() in ['a', 'e', 'i', 'o', 'u']: - return True - else: - return False + return character.lower() in ['a', 'e', 'i', 'o', 'u'] #function to find the number of adjacent vowel pairs. def adjacent_pairs(string): string=string.lower() n=len(string) - count = 0 - for i in range(0,n): - if ((is_vowel(string[i]) and is_vowel(string[i + 1]))): - count += 1 - return count + return sum( + 1 + for i in range(0, n) + if ((is_vowel(string[i]) and is_vowel(string[i + 1]))) + ) #driver code string=input("enter string") diff --git a/data_structures/strings/are_anagrams.py b/data_structures/strings/are_anagrams.py index 7eb7dbc1..c5d1f356 100644 --- a/data_structures/strings/are_anagrams.py +++ b/data_structures/strings/are_anagrams.py @@ -23,10 +23,7 @@ def are_anagrams(string1, string2): xor_value = xor_value ^ ord(string1[i]) xor_value = xor_value ^ ord(string2[i]) - if(xor_value==0): - return True - else: - return False + return xor_value == 0 # Code To test The Function string1 = "thestringsareanagrams" diff --git a/data_structures/strings/check_interleaving_of_strings.py b/data_structures/strings/check_interleaving_of_strings.py index e232ed51..65ba58e9 100644 --- a/data_structures/strings/check_interleaving_of_strings.py +++ b/data_structures/strings/check_interleaving_of_strings.py @@ -49,9 +49,7 @@ def isInterleaving(string_A, string_B, string_C): string_B = input("Enter string B") string_C = input("Enter string C") -result = isInterleaving(string_A, string_B, string_C) - -if(result): - print("String C is interleaving String A and String B") +if result := isInterleaving(string_A, string_B, string_C): + print("String C is interleaving String A and String B") else: - print("String C is not interleaving String A and String B") \ No newline at end of file + print("String C is not interleaving String A and String B") \ No newline at end of file diff --git a/data_structures/strings/check_permutations.py b/data_structures/strings/check_permutations.py index 83ecd6e9..e2d8925a 100644 --- a/data_structures/strings/check_permutations.py +++ b/data_structures/strings/check_permutations.py @@ -20,24 +20,19 @@ def check_permutations(word1, word2): # Case 2: Both strings have a length of zero if len(word1) == 0 and len(word2) == 0: return True - # Case 3: One Letter Strings if len(word1) == 1 and len(word2) == 1: return word1[0] == word2[0] - # Case 4: Length greater than 1 for both strings and lengths are equal - else: - populate_letter_count(word1) + populate_letter_count(word1) # Loop through each letter (looping is an O(n) operation) - for letter in word2: - # Check if it the letter is in the dictionary (checking is O(n) operation) - if letter_counts.get(letter) is not None: - curr_count = letter_counts.get(letter) - if curr_count == 1: - letter_counts.pop(letter) - else: - letter_counts[letter] = curr_count - 1 - else: - return False - return True + for letter in word2: + if letter_counts.get(letter) is None: + return False + curr_count = letter_counts.get(letter) + if curr_count == 1: + letter_counts.pop(letter) + else: + letter_counts[letter] = curr_count - 1 + return True def populate_letter_count(word1): diff --git a/data_structures/strings/one_away.py b/data_structures/strings/one_away.py index 4ea42273..27144aec 100644 --- a/data_structures/strings/one_away.py +++ b/data_structures/strings/one_away.py @@ -51,10 +51,7 @@ def is_one_away(str1, str2): # If one string finished before the other, we will certainly # have one more edit to consider (adding the last letter), so # we must check if the edit counter is still empty - if (i < len(str1) or j < len(str2)) and edit_counter > 0: - return False - - return True + return i >= len(str1) and j >= len(str2) or edit_counter <= 0 # Driver code str1 = input("Enter first string: ") diff --git a/data_structures/strings/rotate_string.py b/data_structures/strings/rotate_string.py index 48edb9d9..7df1a62d 100644 --- a/data_structures/strings/rotate_string.py +++ b/data_structures/strings/rotate_string.py @@ -14,7 +14,7 @@ def is_rotate_string(A, B): return False if len_a == 0: return True - for i in range(len_a): + for _ in range(len_a): A = A[-1:] + A[:-1] if A == B: return True diff --git a/data_structures/strings/unique_char_check.py b/data_structures/strings/unique_char_check.py index 3af3083c..8097753a 100644 --- a/data_structures/strings/unique_char_check.py +++ b/data_structures/strings/unique_char_check.py @@ -16,9 +16,7 @@ def unique_char_check(S): character_count = Counter(S) - if len(character_count) == len(S): - return True - return False + return len(character_count) == len(S) S = input() print(unique_char_check(S)) \ No newline at end of file diff --git a/data_structures/union_find/uf.py b/data_structures/union_find/uf.py index d1f52da3..a29c418c 100644 --- a/data_structures/union_find/uf.py +++ b/data_structures/union_find/uf.py @@ -42,16 +42,13 @@ def union (self, a, b): self.ar[rob] = self.ar[roa] self.size[roa] += self.size[rob] - def find (self, a, b): + def find(self, a, b): ''' Function to check if 'a' and 'b' are connected Input: node number, node number (integers between 0 and n-1) Output: True or False ''' - if self.root (a) == self.root (b): - return True - else: - return False + return self.root (a) == self.root (b) pass