diff --git a/data_structures/arrays/dutch_national_flag.py b/data_structures/arrays/dutch_national_flag.py new file mode 100644 index 000000000000..77193a7963dd --- /dev/null +++ b/data_structures/arrays/dutch_national_flag.py @@ -0,0 +1,39 @@ +def dutch_national_flag(arr: list[int]) -> list[int]: + """ + Sorts an array containing only 0s, 1s and 2s + + Args: + arr(list[int]): The input array (containing only 0s, 1s and 2s) + + Returns: + list[int]: Sorted array + + Examples: + >>> dutch_national_flag([2, 0, 2, 1, 2, 0, 1]) + [0, 0, 1, 1, 2, 2, 2] + >>> dutch_national_flag([0, 1, 2, 0, 1, 2]) + [0, 0, 1, 1, 2, 2] + >>> dutch_national_flag([1, 1, 1]) + [1, 1, 1] + >>> dutch_national_flag([]) + [] + """ + + low, mid, high = 0, 0, len(arr) - 1 + + while mid <= high: + if arr[mid] == 0: + arr[low], arr[mid] = arr[mid], arr[low] + low += 1 + mid += 1 + elif arr[mid] == 1: + mid += 1 + else: + arr[mid], arr[high] = arr[high], arr[mid] + high -= 1 + return arr + + +if __name__ == "__main__": + arr = [2, 0, 2, 1, 2, 0, 1] + print("Sorted array: ", dutch_national_flag(arr)) diff --git a/greedy_methods/fractional_knapsack.py b/greedy_methods/fractional_knapsack.py index d52b56f23569..f7455a9c9fce 100644 --- a/greedy_methods/fractional_knapsack.py +++ b/greedy_methods/fractional_knapsack.py @@ -39,9 +39,11 @@ def frac_knapsack(vl, wt, w, n): return ( 0 if k == 0 - else sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) - if k != n - else sum(vl[:k]) + else ( + sum(vl[:k]) + (w - acc[k - 1]) * (vl[k]) / (wt[k]) + if k != n + else sum(vl[:k]) + ) ) diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index dee9247282f9..5efe0b0e09f3 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -204,9 +204,11 @@ def cofactors(self) -> Matrix: return Matrix( [ [ - self.minors().rows[row][column] - if (row + column) % 2 == 0 - else self.minors().rows[row][column] * -1 + ( + self.minors().rows[row][column] + if (row + column) % 2 == 0 + else self.minors().rows[row][column] * -1 + ) for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows)