From a9eeae9f870750bb60a0944c864184de8cec295e Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 18:20:53 +0530 Subject: [PATCH 01/15] Add string to number converter --- strings/string_to_num.py | 107 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 strings/string_to_num.py diff --git a/strings/string_to_num.py b/strings/string_to_num.py new file mode 100644 index 000000000000..e56abbd39584 --- /dev/null +++ b/strings/string_to_num.py @@ -0,0 +1,107 @@ +''' Converts a given string to integer and float + This works with only Indian system of wording + + * Indian system uses crore, lakh, thousand and not million and billions + + For the part after the decimal example ( .159 ): + * Digit by digit ( .159 ) -> point one five nine is allowed anything else will throw an + error + + >>> "Five" + out:- --> 5 + out:- --> 5.0 + + >>> "One thousand five hundred and two" + out:- --> 1502 + out:- --> 1502.0 + + >>> "Ninety nine crore three lakh seventy two thousand and six point one five nine" + out:- --> 990372006 + out:- --> 990372006.159 + +''' + +def to_int(word): + + if len(word.strip())>0: + units = {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"eleven":11,"twelve":12,"thirteen":13,"fourteen":14,"fifteen":15,"sixteen":16,"seventeen":17,"eighteen":18,"nineteen":19} + + tens = {"ten":10,"twenty":20,"thirty":30,"forty":40,"fifty":50,"sixty":60,"seventy":70,"eighty":80,"ninety":90} + + multiplyers = {"hundred":100,"thousand":1_000,"lakh":1_00_000,"crore":1_00_00_000} + + if "point" in word: + word_lst = word.split("point") + word = "".join(word_lst[:-1]) + + words = word.strip().replace(" and","").replace("-","").replace("_","").lower().split() + + number = 0 # + temp = 0 # + + for index,word in enumerate(words): + if index == 0: + if word in units: + temp += units[word] + elif word in tens: + temp += tens[word] + else: + temp += multiplyers[word] + elif index == (len(words)-1): + if word in units: + temp += units[word] + number += temp + elif word in tens: + temp += tens[word] + number += temp + else: + temp *= multiplyers[word] + number += temp + elif word in units: + temp += units[word] + elif word in tens: + temp += tens[word] + elif word in multiplyers: + temp *= multiplyers[word] + number += temp + temp = 0 + + if len(words)>1: + return(number) + else: + return(temp) + else: + raise ValueError("Empty input is not a valid number in words") + +def to_float(word): + units = {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"eleven":11,"twelve":12,"thirteen":13,"fourteen":14,"fifteen":15,"sixteen":16,"seventeen":17,"eighteen":18,"ninteen":19} + + all_words = word.strip().replace(" and","").replace("-","").replace("_","").lower().split("point") + if len(all_words)>1: + word = all_words[0] + after_point = all_words[1].split() + + integer_part = to_int(word) + + decimal_part = "" + for num in after_point: + if num in units: + decimal_part += str(units[num]) + + str_float = str(integer_part) + str(decimal_part) + divider = ("1" + ("0" * len(after_point))) + return (int(str_float)/int(divider)) + + else: + return(float(to_int(word))) + +if __name__ == "__main__": + while True: + word = input("Enter a number in words (q to quit) :- ").lower().strip() + if word == "q": + break + else: + integer = to_int(word) + print(f"\nThe number in {type(integer)} --> {integer} ") + floater = to_float(word) + print(f"\nThe number in {type(floater)} --> {floater} ") From 2136ec94e190389fff679ed88a9507b5ca0b6905 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 19:02:00 +0530 Subject: [PATCH 02/15] Add string to number converter --- ciphers/base64_cipher.py | 12 +- .../hashing/number_theory/prime_numbers.py | 6 +- data_structures/heap/min_heap.py | 6 +- data_structures/kd_tree/tests/test_kdtree.py | 12 +- .../suffix_tree/tests/test_suffix_tree.py | 24 +-- .../filters/gabor_filter.py | 6 +- dynamic_programming/climbing_stairs.py | 6 +- .../iterating_through_submasks.py | 6 +- financial/time_and_half_pay.py | 18 +- greedy_methods/fractional_knapsack.py | 8 +- machine_learning/frequent_pattern_growth.py | 4 +- .../integration_by_simpson_approx.py | 12 +- maths/prime_check.py | 12 +- maths/primelib.py | 42 ++-- matrix/matrix_class.py | 8 +- neural_network/input_data.py | 6 +- scripts/validate_solutions.py | 6 +- sorts/bead_sort.py | 4 +- strings/min_cost_string_conversion.py | 4 +- strings/string_to_num.py | 203 ++++++++++++------ 20 files changed, 246 insertions(+), 159 deletions(-) diff --git a/ciphers/base64_cipher.py b/ciphers/base64_cipher.py index 038d13963d95..2b950b1be37d 100644 --- a/ciphers/base64_cipher.py +++ b/ciphers/base64_cipher.py @@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes: # Check if the encoded string contains non base64 characters if padding: - assert all(char in B64_CHARSET for char in encoded_data[:-padding]), ( - "Invalid base64 character(s) found." - ) + assert all( + char in B64_CHARSET for char in encoded_data[:-padding] + ), "Invalid base64 character(s) found." else: - assert all(char in B64_CHARSET for char in encoded_data), ( - "Invalid base64 character(s) found." - ) + assert all( + char in B64_CHARSET for char in encoded_data + ), "Invalid base64 character(s) found." # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 82071b5e9f09..2549a1477b2b 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -32,9 +32,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and positive" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index 577b98d788a1..ce7ed570a58d 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -124,9 +124,9 @@ def is_empty(self): return len(self.heap) == 0 def decrease_key(self, node, new_value): - assert self.heap[self.idx_of_element[node]].val > new_value, ( - "newValue must be less that current value" - ) + assert ( + self.heap[self.idx_of_element[node]].val > new_value + ), "newValue must be less that current value" node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node]) diff --git a/data_structures/kd_tree/tests/test_kdtree.py b/data_structures/kd_tree/tests/test_kdtree.py index d6a4a66dd24d..dce5e4f34ff4 100644 --- a/data_structures/kd_tree/tests/test_kdtree.py +++ b/data_structures/kd_tree/tests/test_kdtree.py @@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res assert kdtree is not None, "Expected a KDNode, got None" # Check if root has correct dimensions - assert len(kdtree.point) == num_dimensions, ( - f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" - ) + assert ( + len(kdtree.point) == num_dimensions + ), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" # Check that the tree is balanced to some extent (simplistic check) - assert isinstance(kdtree, KDNode), ( - f"Expected KDNode instance, got {type(kdtree)}" - ) + assert isinstance( + kdtree, KDNode + ), f"Expected KDNode instance, got {type(kdtree)}" def test_nearest_neighbour_search(): diff --git a/data_structures/suffix_tree/tests/test_suffix_tree.py b/data_structures/suffix_tree/tests/test_suffix_tree.py index c9dbe199d19d..45c6790ac48a 100644 --- a/data_structures/suffix_tree/tests/test_suffix_tree.py +++ b/data_structures/suffix_tree/tests/test_suffix_tree.py @@ -22,18 +22,18 @@ def test_search_existing_patterns(self) -> None: patterns = ["ana", "ban", "na"] for pattern in patterns: with self.subTest(pattern=pattern): - assert self.suffix_tree.search(pattern), ( - f"Pattern '{pattern}' should be found." - ) + assert self.suffix_tree.search( + pattern + ), f"Pattern '{pattern}' should be found." def test_search_non_existing_patterns(self) -> None: """Test searching for patterns that do not exist in the suffix tree.""" patterns = ["xyz", "apple", "cat"] for pattern in patterns: with self.subTest(pattern=pattern): - assert not self.suffix_tree.search(pattern), ( - f"Pattern '{pattern}' should not be found." - ) + assert not self.suffix_tree.search( + pattern + ), f"Pattern '{pattern}' should not be found." def test_search_empty_pattern(self) -> None: """Test searching for an empty pattern.""" @@ -41,18 +41,18 @@ def test_search_empty_pattern(self) -> None: def test_search_full_text(self) -> None: """Test searching for the full text.""" - assert self.suffix_tree.search(self.text), ( - "The full text should be found in the suffix tree." - ) + assert self.suffix_tree.search( + self.text + ), "The full text should be found in the suffix tree." def test_search_substrings(self) -> None: """Test searching for substrings of the full text.""" substrings = ["ban", "ana", "a", "na"] for substring in substrings: with self.subTest(substring=substring): - assert self.suffix_tree.search(substring), ( - f"Substring '{substring}' should be found." - ) + assert self.suffix_tree.search( + substring + ), f"Substring '{substring}' should be found." if __name__ == "__main__": diff --git a/digital_image_processing/filters/gabor_filter.py b/digital_image_processing/filters/gabor_filter.py index aaec567f4c99..8f9212a35a79 100644 --- a/digital_image_processing/filters/gabor_filter.py +++ b/digital_image_processing/filters/gabor_filter.py @@ -48,9 +48,9 @@ def gabor_filter_kernel( _y = -sin_theta * px + cos_theta * py # fill kernel - gabor[y, x] = np.exp(-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos( - 2 * np.pi * _x / lambd + psi - ) + gabor[y, x] = np.exp( + -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) + ) * np.cos(2 * np.pi * _x / lambd + psi) return gabor diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index 38bdb427eedc..d6273d025f08 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int: ... AssertionError: number_of_steps needs to be positive integer, your input -7 """ - assert isinstance(number_of_steps, int) and number_of_steps > 0, ( - f"number_of_steps needs to be positive integer, your input {number_of_steps}" - ) + assert ( + isinstance(number_of_steps, int) and number_of_steps > 0 + ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 previous, current = 1, 1 diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index efab6dacff3f..372dd2c74a71 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]: """ - assert isinstance(mask, int) and mask > 0, ( - f"mask needs to be positive integer, your input {mask}" - ) + assert ( + isinstance(mask, int) and mask > 0 + ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed diff --git a/financial/time_and_half_pay.py b/financial/time_and_half_pay.py index c5dff1bc1ce1..3e35c373a4e1 100644 --- a/financial/time_and_half_pay.py +++ b/financial/time_and_half_pay.py @@ -17,15 +17,15 @@ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: 10.0 """ # Check that all input parameters are float or integer - assert isinstance(hours_worked, (float, int)), ( - "Parameter 'hours_worked' must be of type 'int' or 'float'" - ) - assert isinstance(pay_rate, (float, int)), ( - "Parameter 'pay_rate' must be of type 'int' or 'float'" - ) - assert isinstance(hours, (float, int)), ( - "Parameter 'hours' must be of type 'int' or 'float'" - ) + assert isinstance( + hours_worked, (float, int) + ), "Parameter 'hours_worked' must be of type 'int' or 'float'" + assert isinstance( + pay_rate, (float, int) + ), "Parameter 'pay_rate' must be of type 'int' or 'float'" + assert isinstance( + hours, (float, int) + ), "Parameter 'hours' must be of type 'int' or 'float'" normal_pay = hours_worked * pay_rate over_time = max(0, hours_worked - hours) 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/machine_learning/frequent_pattern_growth.py b/machine_learning/frequent_pattern_growth.py index fae2df16efb1..306872cd6e05 100644 --- a/machine_learning/frequent_pattern_growth.py +++ b/machine_learning/frequent_pattern_growth.py @@ -240,7 +240,9 @@ def ascend_tree(leaf_node: TreeNode, prefix_path: list[str]) -> None: ascend_tree(leaf_node.parent, prefix_path) -def find_prefix_path(base_pat: frozenset, tree_node: TreeNode | None) -> dict: # noqa: ARG001 +def find_prefix_path( + base_pat: frozenset, tree_node: TreeNode | None +) -> dict: """ Find the conditional pattern base for a given base pattern. diff --git a/maths/numerical_analysis/integration_by_simpson_approx.py b/maths/numerical_analysis/integration_by_simpson_approx.py index 043f3a9a72af..934299997aac 100644 --- a/maths/numerical_analysis/integration_by_simpson_approx.py +++ b/maths/numerical_analysis/integration_by_simpson_approx.py @@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo AssertionError: precision should be positive integer your input : -1 """ - assert callable(function), ( - f"the function(object) passed should be callable your input : {function}" - ) + assert callable( + function + ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" - assert isinstance(precision, int) and precision > 0, ( - f"precision should be positive integer your input : {precision}" - ) + assert ( + isinstance(precision, int) and precision > 0 + ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function diff --git a/maths/prime_check.py b/maths/prime_check.py index a757c4108f24..f1bc4def2469 100644 --- a/maths/prime_check.py +++ b/maths/prime_check.py @@ -73,12 +73,12 @@ def test_primes(self): def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) - assert not is_prime(0), ( - "Zero doesn't have any positive factors, primes must have exactly two." - ) - assert not is_prime(1), ( - "One only has 1 positive factor, primes must have exactly two." - ) + assert not is_prime( + 0 + ), "Zero doesn't have any positive factors, primes must have exactly two." + assert not is_prime( + 1 + ), "One only has 1 positive factor, primes must have exactly two." assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) diff --git a/maths/primelib.py b/maths/primelib.py index 9f031efc50a9..c41aa07e09c4 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -66,9 +66,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and positive" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and positive" status = True @@ -254,9 +254,9 @@ def greatest_prime_factor(number): """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and >= 0" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and >= 0" ans = 0 @@ -296,9 +296,9 @@ def smallest_prime_factor(number): """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and >= 0" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and >= 0" ans = 0 @@ -399,9 +399,9 @@ def goldbach(number): """ # precondition - assert isinstance(number, int) and (number > 2) and is_even(number), ( - "'number' must been an int, even and > 2" - ) + assert ( + isinstance(number, int) and (number > 2) and is_even(number) + ), "'number' must been an int, even and > 2" ans = [] # this list will returned @@ -525,9 +525,9 @@ def kg_v(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and (ans >= 0), ( - "'ans' must been from type int and positive" - ) + assert isinstance(ans, int) and ( + ans >= 0 + ), "'ans' must been from type int and positive" return ans @@ -574,9 +574,9 @@ def get_prime(n): ans += 1 # precondition - assert isinstance(ans, int) and is_prime(ans), ( - "'ans' must been a prime number and from type int" - ) + assert isinstance(ans, int) and is_prime( + ans + ), "'ans' must been a prime number and from type int" return ans @@ -705,9 +705,9 @@ def is_perfect_number(number): """ # precondition - assert isinstance(number, int) and (number > 1), ( - "'number' must been an int and >= 1" - ) + assert isinstance(number, int) and ( + number > 1 + ), "'number' must been an int and >= 1" divisors = get_divisors(number) 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) diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 3a8628f939f8..72debabb566a 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -160,9 +160,9 @@ def __init__( self._num_examples = 10000 self.one_hot = one_hot else: - assert images.shape[0] == labels.shape[0], ( - f"images.shape: {images.shape} labels.shape: {labels.shape}" - ) + assert ( + images.shape[0] == labels.shape[0] + ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] diff --git a/scripts/validate_solutions.py b/scripts/validate_solutions.py index f426153b5683..79a2f790081f 100755 --- a/scripts/validate_solutions.py +++ b/scripts/validate_solutions.py @@ -103,6 +103,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None: solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() - assert answer == expected, ( - f"Expected solution to {problem_number} to have hash {expected}, got {answer}" - ) + assert ( + answer == expected + ), f"Expected solution to {problem_number} to have hash {expected}, got {answer}" diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 8ce0619fd573..2f175162164c 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -31,7 +31,9 @@ def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for _ in range(len(sequence)): - for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): # noqa: RUF007 + for i, (rod_upper, rod_lower) in enumerate( + zip(sequence, sequence[1:]) + ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index 87eb5189e16a..d1c22f0176cb 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -140,7 +140,9 @@ def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: elif op[0] == "R": string[i] = op[2] - file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) # noqa: UP031 + file.write( + "%-16s" % ("Replace %c" % op[1] + " with " + str(op[2])) + ) file.write("\t\t" + "".join(string)) file.write("\r\n") diff --git a/strings/string_to_num.py b/strings/string_to_num.py index e56abbd39584..f29bec6f3e9e 100644 --- a/strings/string_to_num.py +++ b/strings/string_to_num.py @@ -1,45 +1,91 @@ -''' Converts a given string to integer and float - This works with only Indian system of wording - - * Indian system uses crore, lakh, thousand and not million and billions - - For the part after the decimal example ( .159 ): - * Digit by digit ( .159 ) -> point one five nine is allowed anything else will throw an - error - - >>> "Five" - out:- --> 5 - out:- --> 5.0 - - >>> "One thousand five hundred and two" - out:- --> 1502 - out:- --> 1502.0 - - >>> "Ninety nine crore three lakh seventy two thousand and six point one five nine" - out:- --> 990372006 - out:- --> 990372006.159 - +'''Converts a given string to integer and float +This works with only Indian system of wording + + * Indian system uses crore, lakh, thousand and not million and billions + +For the part after the decimal example ( .159 ): + * Digit by digit ( .159 ) -> point one five nine is allowed anything else will throw an error + +>>> to_int("Five") +5 +>>> to_float("Five") +5.0 + +>>> to_int("One thousand five hundred and two") +1502 +>>> to_float("One thousand five hundred and two") +1502.0 + +>>> to_int("Ninety nine crore three lakh seventy two thousand and six point one five nine") +990372006 +>>> to_float("Ninety nine crore three lakh seventy two thousand and six point one five nine") +990372006.159 + +wikipedia explanation - https://en.wikipedia.org/wiki/Numeral_(linguistics) ''' -def to_int(word): - - if len(word.strip())>0: - units = {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"eleven":11,"twelve":12,"thirteen":13,"fourteen":14,"fifteen":15,"sixteen":16,"seventeen":17,"eighteen":18,"nineteen":19} - - tens = {"ten":10,"twenty":20,"thirty":30,"forty":40,"fifty":50,"sixty":60,"seventy":70,"eighty":80,"ninety":90} - - multiplyers = {"hundred":100,"thousand":1_000,"lakh":1_00_000,"crore":1_00_00_000} - + +def to_int(word : str) -> int: + + if len(word.strip()) > 0: + units = { + "zero": 0, + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + "eleven": 11, + "twelve": 12, + "thirteen": 13, + "fourteen": 14, + "fifteen": 15, + "sixteen": 16, + "seventeen": 17, + "eighteen": 18, + "nineteen": 19, + } + + tens = { + "ten": 10, + "twenty": 20, + "thirty": 30, + "forty": 40, + "fifty": 50, + "sixty": 60, + "seventy": 70, + "eighty": 80, + "ninety": 90, + } + + multiplyers = { + "hundred": 100, + "thousand": 1_000, + "lakh": 1_00_000, + "crore": 1_00_00_000, + } + if "point" in word: word_lst = word.split("point") word = "".join(word_lst[:-1]) - - words = word.strip().replace(" and","").replace("-","").replace("_","").lower().split() - - number = 0 # - temp = 0 # - - for index,word in enumerate(words): + + words = ( + word.strip() + .replace(" and", "") + .replace("-", "") + .replace("_", "") + .lower() + .split() + ) + + number = 0 + temp = 0 + + for index, word in enumerate(words): if index == 0: if word in units: temp += units[word] @@ -47,7 +93,7 @@ def to_int(word): temp += tens[word] else: temp += multiplyers[word] - elif index == (len(words)-1): + elif index == (len(words) - 1): if word in units: temp += units[word] number += temp @@ -65,43 +111,74 @@ def to_int(word): temp *= multiplyers[word] number += temp temp = 0 - - if len(words)>1: - return(number) + + if len(words) > 1: + return number else: - return(temp) + return temp else: raise ValueError("Empty input is not a valid number in words") -def to_float(word): - units = {"zero":0,"one":1,"two":2,"three":3,"four":4,"five":5,"six":6,"seven":7,"eight":8,"nine":9,"eleven":11,"twelve":12,"thirteen":13,"fourteen":14,"fifteen":15,"sixteen":16,"seventeen":17,"eighteen":18,"ninteen":19} - - all_words = word.strip().replace(" and","").replace("-","").replace("_","").lower().split("point") - if len(all_words)>1: + +def to_float(word : str)-> float: + units = { + "zero": 0, + "one": 1, + "two": 2, + "three": 3, + "four": 4, + "five": 5, + "six": 6, + "seven": 7, + "eight": 8, + "nine": 9, + "eleven": 11, + "twelve": 12, + "thirteen": 13, + "fourteen": 14, + "fifteen": 15, + "sixteen": 16, + "seventeen": 17, + "eighteen": 18, + "nineteen": 19, + } + + all_words = ( + word.strip() + .replace(" and", "") + .replace("-", "") + .replace("_", "") + .lower() + .split("point") + ) + if len(all_words) > 1: word = all_words[0] after_point = all_words[1].split() - + integer_part = to_int(word) decimal_part = "" for num in after_point: if num in units: - decimal_part += str(units[num]) - + decimal_part += str(units[num]) + str_float = str(integer_part) + str(decimal_part) - divider = ("1" + ("0" * len(after_point))) - return (int(str_float)/int(divider)) - + divider = "1" + ("0" * len(after_point)) + return int(str_float) / int(divider) + else: - return(float(to_int(word))) + return float(to_int(word)) + if __name__ == "__main__": - while True: - word = input("Enter a number in words (q to quit) :- ").lower().strip() - if word == "q": - break - else: - integer = to_int(word) - print(f"\nThe number in {type(integer)} --> {integer} ") - floater = to_float(word) - print(f"\nThe number in {type(floater)} --> {floater} ") + import doctest + doctest.testmod() + # while True: + # word = input("Enter a number in words (q to quit) :- ").lower().strip() + # if word == "q": + # break + # else: + # integer = to_int(word) + # print(f"\nThe number in {type(integer)} --> {integer} ") + # floater = to_float(word) + # print(f"\nThe number in {type(floater)} --> {floater} ") From 8e680fc316b4fd3cc2053f16bbb5ff281a98ea77 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Oct 2025 13:34:58 +0000 Subject: [PATCH 03/15] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- ciphers/base64_cipher.py | 12 +++--- .../hashing/number_theory/prime_numbers.py | 6 +-- data_structures/heap/min_heap.py | 6 +-- data_structures/kd_tree/tests/test_kdtree.py | 12 +++--- .../suffix_tree/tests/test_suffix_tree.py | 24 +++++------ .../filters/gabor_filter.py | 6 +-- dynamic_programming/climbing_stairs.py | 6 +-- .../iterating_through_submasks.py | 6 +-- financial/time_and_half_pay.py | 18 ++++---- machine_learning/frequent_pattern_growth.py | 4 +- .../integration_by_simpson_approx.py | 12 +++--- maths/prime_check.py | 12 +++--- maths/primelib.py | 42 +++++++++---------- neural_network/input_data.py | 6 +-- scripts/validate_solutions.py | 6 +-- sorts/bead_sort.py | 4 +- strings/min_cost_string_conversion.py | 4 +- strings/string_to_num.py | 10 ++--- 18 files changed, 95 insertions(+), 101 deletions(-) diff --git a/ciphers/base64_cipher.py b/ciphers/base64_cipher.py index 2b950b1be37d..038d13963d95 100644 --- a/ciphers/base64_cipher.py +++ b/ciphers/base64_cipher.py @@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes: # Check if the encoded string contains non base64 characters if padding: - assert all( - char in B64_CHARSET for char in encoded_data[:-padding] - ), "Invalid base64 character(s) found." + assert all(char in B64_CHARSET for char in encoded_data[:-padding]), ( + "Invalid base64 character(s) found." + ) else: - assert all( - char in B64_CHARSET for char in encoded_data - ), "Invalid base64 character(s) found." + assert all(char in B64_CHARSET for char in encoded_data), ( + "Invalid base64 character(s) found." + ) # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 2549a1477b2b..82071b5e9f09 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -32,9 +32,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and positive" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and positive" + ) if 1 < number < 4: # 2 and 3 are primes diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index ce7ed570a58d..577b98d788a1 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -124,9 +124,9 @@ def is_empty(self): return len(self.heap) == 0 def decrease_key(self, node, new_value): - assert ( - self.heap[self.idx_of_element[node]].val > new_value - ), "newValue must be less that current value" + assert self.heap[self.idx_of_element[node]].val > new_value, ( + "newValue must be less that current value" + ) node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node]) diff --git a/data_structures/kd_tree/tests/test_kdtree.py b/data_structures/kd_tree/tests/test_kdtree.py index dce5e4f34ff4..d6a4a66dd24d 100644 --- a/data_structures/kd_tree/tests/test_kdtree.py +++ b/data_structures/kd_tree/tests/test_kdtree.py @@ -48,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res assert kdtree is not None, "Expected a KDNode, got None" # Check if root has correct dimensions - assert ( - len(kdtree.point) == num_dimensions - ), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" + assert len(kdtree.point) == num_dimensions, ( + f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" + ) # Check that the tree is balanced to some extent (simplistic check) - assert isinstance( - kdtree, KDNode - ), f"Expected KDNode instance, got {type(kdtree)}" + assert isinstance(kdtree, KDNode), ( + f"Expected KDNode instance, got {type(kdtree)}" + ) def test_nearest_neighbour_search(): diff --git a/data_structures/suffix_tree/tests/test_suffix_tree.py b/data_structures/suffix_tree/tests/test_suffix_tree.py index 45c6790ac48a..c9dbe199d19d 100644 --- a/data_structures/suffix_tree/tests/test_suffix_tree.py +++ b/data_structures/suffix_tree/tests/test_suffix_tree.py @@ -22,18 +22,18 @@ def test_search_existing_patterns(self) -> None: patterns = ["ana", "ban", "na"] for pattern in patterns: with self.subTest(pattern=pattern): - assert self.suffix_tree.search( - pattern - ), f"Pattern '{pattern}' should be found." + assert self.suffix_tree.search(pattern), ( + f"Pattern '{pattern}' should be found." + ) def test_search_non_existing_patterns(self) -> None: """Test searching for patterns that do not exist in the suffix tree.""" patterns = ["xyz", "apple", "cat"] for pattern in patterns: with self.subTest(pattern=pattern): - assert not self.suffix_tree.search( - pattern - ), f"Pattern '{pattern}' should not be found." + assert not self.suffix_tree.search(pattern), ( + f"Pattern '{pattern}' should not be found." + ) def test_search_empty_pattern(self) -> None: """Test searching for an empty pattern.""" @@ -41,18 +41,18 @@ def test_search_empty_pattern(self) -> None: def test_search_full_text(self) -> None: """Test searching for the full text.""" - assert self.suffix_tree.search( - self.text - ), "The full text should be found in the suffix tree." + assert self.suffix_tree.search(self.text), ( + "The full text should be found in the suffix tree." + ) def test_search_substrings(self) -> None: """Test searching for substrings of the full text.""" substrings = ["ban", "ana", "a", "na"] for substring in substrings: with self.subTest(substring=substring): - assert self.suffix_tree.search( - substring - ), f"Substring '{substring}' should be found." + assert self.suffix_tree.search(substring), ( + f"Substring '{substring}' should be found." + ) if __name__ == "__main__": diff --git a/digital_image_processing/filters/gabor_filter.py b/digital_image_processing/filters/gabor_filter.py index 8f9212a35a79..aaec567f4c99 100644 --- a/digital_image_processing/filters/gabor_filter.py +++ b/digital_image_processing/filters/gabor_filter.py @@ -48,9 +48,9 @@ def gabor_filter_kernel( _y = -sin_theta * px + cos_theta * py # fill kernel - gabor[y, x] = np.exp( - -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) - ) * np.cos(2 * np.pi * _x / lambd + psi) + gabor[y, x] = np.exp(-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos( + 2 * np.pi * _x / lambd + psi + ) return gabor diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index d6273d025f08..38bdb427eedc 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int: ... AssertionError: number_of_steps needs to be positive integer, your input -7 """ - assert ( - isinstance(number_of_steps, int) and number_of_steps > 0 - ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" + assert isinstance(number_of_steps, int) and number_of_steps > 0, ( + f"number_of_steps needs to be positive integer, your input {number_of_steps}" + ) if number_of_steps == 1: return 1 previous, current = 1, 1 diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index 372dd2c74a71..efab6dacff3f 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]: """ - assert ( - isinstance(mask, int) and mask > 0 - ), f"mask needs to be positive integer, your input {mask}" + assert isinstance(mask, int) and mask > 0, ( + f"mask needs to be positive integer, your input {mask}" + ) """ first submask iterated will be mask itself then operation will be performed diff --git a/financial/time_and_half_pay.py b/financial/time_and_half_pay.py index 3e35c373a4e1..c5dff1bc1ce1 100644 --- a/financial/time_and_half_pay.py +++ b/financial/time_and_half_pay.py @@ -17,15 +17,15 @@ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: 10.0 """ # Check that all input parameters are float or integer - assert isinstance( - hours_worked, (float, int) - ), "Parameter 'hours_worked' must be of type 'int' or 'float'" - assert isinstance( - pay_rate, (float, int) - ), "Parameter 'pay_rate' must be of type 'int' or 'float'" - assert isinstance( - hours, (float, int) - ), "Parameter 'hours' must be of type 'int' or 'float'" + assert isinstance(hours_worked, (float, int)), ( + "Parameter 'hours_worked' must be of type 'int' or 'float'" + ) + assert isinstance(pay_rate, (float, int)), ( + "Parameter 'pay_rate' must be of type 'int' or 'float'" + ) + assert isinstance(hours, (float, int)), ( + "Parameter 'hours' must be of type 'int' or 'float'" + ) normal_pay = hours_worked * pay_rate over_time = max(0, hours_worked - hours) diff --git a/machine_learning/frequent_pattern_growth.py b/machine_learning/frequent_pattern_growth.py index 306872cd6e05..c2a5e640c0bb 100644 --- a/machine_learning/frequent_pattern_growth.py +++ b/machine_learning/frequent_pattern_growth.py @@ -240,9 +240,7 @@ def ascend_tree(leaf_node: TreeNode, prefix_path: list[str]) -> None: ascend_tree(leaf_node.parent, prefix_path) -def find_prefix_path( - base_pat: frozenset, tree_node: TreeNode | None -) -> dict: +def find_prefix_path(base_pat: frozenset, tree_node: TreeNode | None) -> dict: """ Find the conditional pattern base for a given base pattern. diff --git a/maths/numerical_analysis/integration_by_simpson_approx.py b/maths/numerical_analysis/integration_by_simpson_approx.py index 934299997aac..043f3a9a72af 100644 --- a/maths/numerical_analysis/integration_by_simpson_approx.py +++ b/maths/numerical_analysis/integration_by_simpson_approx.py @@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo AssertionError: precision should be positive integer your input : -1 """ - assert callable( - function - ), f"the function(object) passed should be callable your input : {function}" + assert callable(function), ( + f"the function(object) passed should be callable your input : {function}" + ) assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" - assert ( - isinstance(precision, int) and precision > 0 - ), f"precision should be positive integer your input : {precision}" + assert isinstance(precision, int) and precision > 0, ( + f"precision should be positive integer your input : {precision}" + ) # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function diff --git a/maths/prime_check.py b/maths/prime_check.py index f1bc4def2469..a757c4108f24 100644 --- a/maths/prime_check.py +++ b/maths/prime_check.py @@ -73,12 +73,12 @@ def test_primes(self): def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) - assert not is_prime( - 0 - ), "Zero doesn't have any positive factors, primes must have exactly two." - assert not is_prime( - 1 - ), "One only has 1 positive factor, primes must have exactly two." + assert not is_prime(0), ( + "Zero doesn't have any positive factors, primes must have exactly two." + ) + assert not is_prime(1), ( + "One only has 1 positive factor, primes must have exactly two." + ) assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) diff --git a/maths/primelib.py b/maths/primelib.py index c41aa07e09c4..9f031efc50a9 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -66,9 +66,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and positive" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and positive" + ) status = True @@ -254,9 +254,9 @@ def greatest_prime_factor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and >= 0" + ) ans = 0 @@ -296,9 +296,9 @@ def smallest_prime_factor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and >= 0" + ) ans = 0 @@ -399,9 +399,9 @@ def goldbach(number): """ # precondition - assert ( - isinstance(number, int) and (number > 2) and is_even(number) - ), "'number' must been an int, even and > 2" + assert isinstance(number, int) and (number > 2) and is_even(number), ( + "'number' must been an int, even and > 2" + ) ans = [] # this list will returned @@ -525,9 +525,9 @@ def kg_v(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and ( - ans >= 0 - ), "'ans' must been from type int and positive" + assert isinstance(ans, int) and (ans >= 0), ( + "'ans' must been from type int and positive" + ) return ans @@ -574,9 +574,9 @@ def get_prime(n): ans += 1 # precondition - assert isinstance(ans, int) and is_prime( - ans - ), "'ans' must been a prime number and from type int" + assert isinstance(ans, int) and is_prime(ans), ( + "'ans' must been a prime number and from type int" + ) return ans @@ -705,9 +705,9 @@ def is_perfect_number(number): """ # precondition - assert isinstance(number, int) and ( - number > 1 - ), "'number' must been an int and >= 1" + assert isinstance(number, int) and (number > 1), ( + "'number' must been an int and >= 1" + ) divisors = get_divisors(number) diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 72debabb566a..3a8628f939f8 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -160,9 +160,9 @@ def __init__( self._num_examples = 10000 self.one_hot = one_hot else: - assert ( - images.shape[0] == labels.shape[0] - ), f"images.shape: {images.shape} labels.shape: {labels.shape}" + assert images.shape[0] == labels.shape[0], ( + f"images.shape: {images.shape} labels.shape: {labels.shape}" + ) self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] diff --git a/scripts/validate_solutions.py b/scripts/validate_solutions.py index 79a2f790081f..f426153b5683 100755 --- a/scripts/validate_solutions.py +++ b/scripts/validate_solutions.py @@ -103,6 +103,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None: solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() - assert ( - answer == expected - ), f"Expected solution to {problem_number} to have hash {expected}, got {answer}" + assert answer == expected, ( + f"Expected solution to {problem_number} to have hash {expected}, got {answer}" + ) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 2f175162164c..e51173643d81 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -31,9 +31,7 @@ def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for _ in range(len(sequence)): - for i, (rod_upper, rod_lower) in enumerate( - zip(sequence, sequence[1:]) - ): + for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index d1c22f0176cb..363f46755e08 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -140,9 +140,7 @@ def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: elif op[0] == "R": string[i] = op[2] - file.write( - "%-16s" % ("Replace %c" % op[1] + " with " + str(op[2])) - ) + file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") diff --git a/strings/string_to_num.py b/strings/string_to_num.py index f29bec6f3e9e..c859acd5dcd9 100644 --- a/strings/string_to_num.py +++ b/strings/string_to_num.py @@ -1,4 +1,4 @@ -'''Converts a given string to integer and float +"""Converts a given string to integer and float This works with only Indian system of wording * Indian system uses crore, lakh, thousand and not million and billions @@ -22,11 +22,10 @@ 990372006.159 wikipedia explanation - https://en.wikipedia.org/wiki/Numeral_(linguistics) -''' +""" -def to_int(word : str) -> int: - +def to_int(word: str) -> int: if len(word.strip()) > 0: units = { "zero": 0, @@ -120,7 +119,7 @@ def to_int(word : str) -> int: raise ValueError("Empty input is not a valid number in words") -def to_float(word : str)-> float: +def to_float(word: str) -> float: units = { "zero": 0, "one": 1, @@ -172,6 +171,7 @@ def to_float(word : str)-> float: if __name__ == "__main__": import doctest + doctest.testmod() # while True: # word = input("Enter a number in words (q to quit) :- ").lower().strip() From 59bb29b692b979bc72686eab4484a02f52e609e5 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 19:29:54 +0530 Subject: [PATCH 04/15] Solved ruff check in str_to_num.py --- strings/string_to_num.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/strings/string_to_num.py b/strings/string_to_num.py index c859acd5dcd9..710683273067 100644 --- a/strings/string_to_num.py +++ b/strings/string_to_num.py @@ -4,7 +4,8 @@ * Indian system uses crore, lakh, thousand and not million and billions For the part after the decimal example ( .159 ): - * Digit by digit ( .159 ) -> point one five nine is allowed anything else will throw an error + * Digit by digit ( .159 ) -> point one five nine is allowed + * Anything else will throw an error >>> to_int("Five") 5 @@ -16,9 +17,14 @@ >>> to_float("One thousand five hundred and two") 1502.0 ->>> to_int("Ninety nine crore three lakh seventy two thousand and six point one five nine") +>>> to_int( +... "Ninety nine crore three lakh seventy two thousand and six point one five nine" +... ) 990372006 ->>> to_float("Ninety nine crore three lakh seventy two thousand and six point one five nine") + +>>> to_float( +... "Ninety nine crore three lakh seventy two thousand and six point one five nine" +... ) 990372006.159 wikipedia explanation - https://en.wikipedia.org/wiki/Numeral_(linguistics) From e755bbfee08afddbbf53113fc534036659975947 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 19:52:51 +0530 Subject: [PATCH 05/15] Fix ruff check for machine_learning/frequent_pattern_growth.py:243:22 --- machine_learning/frequent_pattern_growth.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/machine_learning/frequent_pattern_growth.py b/machine_learning/frequent_pattern_growth.py index c2a5e640c0bb..9f1817df2fb3 100644 --- a/machine_learning/frequent_pattern_growth.py +++ b/machine_learning/frequent_pattern_growth.py @@ -240,7 +240,7 @@ def ascend_tree(leaf_node: TreeNode, prefix_path: list[str]) -> None: ascend_tree(leaf_node.parent, prefix_path) -def find_prefix_path(base_pat: frozenset, tree_node: TreeNode | None) -> dict: +def find_prefix_path(_base_pat: frozenset, tree_node: TreeNode | None) -> dict: """ Find the conditional pattern base for a given base pattern. From f488a07b8317c97639cb1b1f37a746bc2214cdc9 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 19:57:33 +0530 Subject: [PATCH 06/15] Fix ruff check for sorts/bead_sort.py:34:52 --- sorts/bead_sort.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index e51173643d81..64a0d71c5a93 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -28,13 +28,13 @@ def bead_sort(sequence: list) -> list: ... TypeError: Sequence must be list of non-negative integers """ + from itertools import pairwise if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") - for _ in range(len(sequence)): - for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): - if rod_upper > rod_lower: - sequence[i] -= rod_upper - rod_lower - sequence[i + 1] += rod_upper - rod_lower + for i, (rod_upper, rod_lower) in enumerate(pairwise(sequence)): + if rod_upper > rod_lower: + sequence[i] -= rod_upper - rod_lower + sequence[i + 1] += rod_upper - rod_lower return sequence From 5673c86e848405453dcd2d4d6dd0f7dbdd93b320 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 20:00:42 +0530 Subject: [PATCH 07/15] Fix ruff check for strings/min_cost_string_conversion.py:143:39 --- strings/min_cost_string_conversion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strings/min_cost_string_conversion.py b/strings/min_cost_string_conversion.py index 363f46755e08..70cd08d6faf4 100644 --- a/strings/min_cost_string_conversion.py +++ b/strings/min_cost_string_conversion.py @@ -140,7 +140,7 @@ def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: elif op[0] == "R": string[i] = op[2] - file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) + file.write(f"{'Replace ' + op[1] + ' with ' + str(op[2]):<16}") file.write("\t\t" + "".join(string)) file.write("\r\n") From 99648243e44273dbac8f44d20ad4766c710906df Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Oct 2025 14:32:22 +0000 Subject: [PATCH 08/15] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/bead_sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 64a0d71c5a93..8335eb2cef36 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -29,6 +29,7 @@ def bead_sort(sequence: list) -> list: TypeError: Sequence must be list of non-negative integers """ from itertools import pairwise + if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for i, (rod_upper, rod_lower) in enumerate(pairwise(sequence)): From 3f30ca2cb86e5e172511b5530ced9e81a9358b72 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 20:05:06 +0530 Subject: [PATCH 09/15] Solved codespell --- ciphers/base64_cipher.py | 12 +++--- computer_vision/cnn_classification.py | 1 - .../hashing/number_theory/prime_numbers.py | 6 +-- data_structures/heap/min_heap.py | 6 +-- .../kd_tree/example/example_usage.py | 3 +- data_structures/kd_tree/tests/test_kdtree.py | 15 +++---- .../suffix_tree/tests/test_suffix_tree.py | 24 +++++------ .../filters/gabor_filter.py | 9 ++-- .../filters/laplacian_filter.py | 12 +----- dynamic_programming/climbing_stairs.py | 6 +-- .../iterating_through_submasks.py | 6 +-- financial/time_and_half_pay.py | 18 ++++---- linear_algebra/src/test_linear_algebra.py | 10 +---- .../integration_by_simpson_approx.py | 12 +++--- maths/prime_check.py | 12 +++--- maths/primelib.py | 42 +++++++++---------- matrix/tests/test_matrix_operation.py | 1 - neural_network/input_data.py | 6 +-- other/password.py | 3 +- quantum/q_fourier_transform.py | 3 +- quantum/quantum_teleportation.py.DISABLED.txt | 3 +- scripts/validate_solutions.py | 6 +-- strings/string_to_num.py | 10 ++--- 23 files changed, 108 insertions(+), 118 deletions(-) diff --git a/ciphers/base64_cipher.py b/ciphers/base64_cipher.py index 038d13963d95..2b950b1be37d 100644 --- a/ciphers/base64_cipher.py +++ b/ciphers/base64_cipher.py @@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes: # Check if the encoded string contains non base64 characters if padding: - assert all(char in B64_CHARSET for char in encoded_data[:-padding]), ( - "Invalid base64 character(s) found." - ) + assert all( + char in B64_CHARSET for char in encoded_data[:-padding] + ), "Invalid base64 character(s) found." else: - assert all(char in B64_CHARSET for char in encoded_data), ( - "Invalid base64 character(s) found." - ) + assert all( + char in B64_CHARSET for char in encoded_data + ), "Invalid base64 character(s) found." # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" diff --git a/computer_vision/cnn_classification.py b/computer_vision/cnn_classification.py index 115333eba0d1..5d02ee70b4f6 100644 --- a/computer_vision/cnn_classification.py +++ b/computer_vision/cnn_classification.py @@ -22,7 +22,6 @@ # Part 1 - Building the CNN import numpy as np - # Importing the Keras libraries and packages import tensorflow as tf from keras import layers, models diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 82071b5e9f09..2549a1477b2b 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -32,9 +32,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and positive" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index 577b98d788a1..ce7ed570a58d 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -124,9 +124,9 @@ def is_empty(self): return len(self.heap) == 0 def decrease_key(self, node, new_value): - assert self.heap[self.idx_of_element[node]].val > new_value, ( - "newValue must be less that current value" - ) + assert ( + self.heap[self.idx_of_element[node]].val > new_value + ), "newValue must be less that current value" node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node]) diff --git a/data_structures/kd_tree/example/example_usage.py b/data_structures/kd_tree/example/example_usage.py index 892c3b8c4a2a..ec85d8d3183a 100644 --- a/data_structures/kd_tree/example/example_usage.py +++ b/data_structures/kd_tree/example/example_usage.py @@ -10,7 +10,8 @@ from data_structures.kd_tree.build_kdtree import build_kdtree from data_structures.kd_tree.example.hypercube_points import hypercube_points -from data_structures.kd_tree.nearest_neighbour_search import nearest_neighbour_search +from data_structures.kd_tree.nearest_neighbour_search import \ + nearest_neighbour_search def main() -> None: diff --git a/data_structures/kd_tree/tests/test_kdtree.py b/data_structures/kd_tree/tests/test_kdtree.py index d6a4a66dd24d..e882b0426296 100644 --- a/data_structures/kd_tree/tests/test_kdtree.py +++ b/data_structures/kd_tree/tests/test_kdtree.py @@ -12,7 +12,8 @@ from data_structures.kd_tree.build_kdtree import build_kdtree from data_structures.kd_tree.example.hypercube_points import hypercube_points from data_structures.kd_tree.kd_node import KDNode -from data_structures.kd_tree.nearest_neighbour_search import nearest_neighbour_search +from data_structures.kd_tree.nearest_neighbour_search import \ + nearest_neighbour_search @pytest.mark.parametrize( @@ -48,14 +49,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res assert kdtree is not None, "Expected a KDNode, got None" # Check if root has correct dimensions - assert len(kdtree.point) == num_dimensions, ( - f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" - ) + assert ( + len(kdtree.point) == num_dimensions + ), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" # Check that the tree is balanced to some extent (simplistic check) - assert isinstance(kdtree, KDNode), ( - f"Expected KDNode instance, got {type(kdtree)}" - ) + assert isinstance( + kdtree, KDNode + ), f"Expected KDNode instance, got {type(kdtree)}" def test_nearest_neighbour_search(): diff --git a/data_structures/suffix_tree/tests/test_suffix_tree.py b/data_structures/suffix_tree/tests/test_suffix_tree.py index c9dbe199d19d..45c6790ac48a 100644 --- a/data_structures/suffix_tree/tests/test_suffix_tree.py +++ b/data_structures/suffix_tree/tests/test_suffix_tree.py @@ -22,18 +22,18 @@ def test_search_existing_patterns(self) -> None: patterns = ["ana", "ban", "na"] for pattern in patterns: with self.subTest(pattern=pattern): - assert self.suffix_tree.search(pattern), ( - f"Pattern '{pattern}' should be found." - ) + assert self.suffix_tree.search( + pattern + ), f"Pattern '{pattern}' should be found." def test_search_non_existing_patterns(self) -> None: """Test searching for patterns that do not exist in the suffix tree.""" patterns = ["xyz", "apple", "cat"] for pattern in patterns: with self.subTest(pattern=pattern): - assert not self.suffix_tree.search(pattern), ( - f"Pattern '{pattern}' should not be found." - ) + assert not self.suffix_tree.search( + pattern + ), f"Pattern '{pattern}' should not be found." def test_search_empty_pattern(self) -> None: """Test searching for an empty pattern.""" @@ -41,18 +41,18 @@ def test_search_empty_pattern(self) -> None: def test_search_full_text(self) -> None: """Test searching for the full text.""" - assert self.suffix_tree.search(self.text), ( - "The full text should be found in the suffix tree." - ) + assert self.suffix_tree.search( + self.text + ), "The full text should be found in the suffix tree." def test_search_substrings(self) -> None: """Test searching for substrings of the full text.""" substrings = ["ban", "ana", "a", "na"] for substring in substrings: with self.subTest(substring=substring): - assert self.suffix_tree.search(substring), ( - f"Substring '{substring}' should be found." - ) + assert self.suffix_tree.search( + substring + ), f"Substring '{substring}' should be found." if __name__ == "__main__": diff --git a/digital_image_processing/filters/gabor_filter.py b/digital_image_processing/filters/gabor_filter.py index aaec567f4c99..954997b894c8 100644 --- a/digital_image_processing/filters/gabor_filter.py +++ b/digital_image_processing/filters/gabor_filter.py @@ -1,7 +1,8 @@ # Implementation of the Gaborfilter # https://en.wikipedia.org/wiki/Gabor_filter import numpy as np -from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey +from cv2 import (COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, + waitKey) def gabor_filter_kernel( @@ -48,9 +49,9 @@ def gabor_filter_kernel( _y = -sin_theta * px + cos_theta * py # fill kernel - gabor[y, x] = np.exp(-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos( - 2 * np.pi * _x / lambd + psi - ) + gabor[y, x] = np.exp( + -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) + ) * np.cos(2 * np.pi * _x / lambd + psi) return gabor diff --git a/digital_image_processing/filters/laplacian_filter.py b/digital_image_processing/filters/laplacian_filter.py index 69b9616e4d30..d5b88ae5a98d 100644 --- a/digital_image_processing/filters/laplacian_filter.py +++ b/digital_image_processing/filters/laplacian_filter.py @@ -3,16 +3,8 @@ # @Date : 10/04/2023 import numpy as np -from cv2 import ( - BORDER_DEFAULT, - COLOR_BGR2GRAY, - CV_64F, - cvtColor, - filter2D, - imread, - imshow, - waitKey, -) +from cv2 import (BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, + imread, imshow, waitKey) from digital_image_processing.filters.gaussian_filter import gaussian_filter diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index 38bdb427eedc..d6273d025f08 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int: ... AssertionError: number_of_steps needs to be positive integer, your input -7 """ - assert isinstance(number_of_steps, int) and number_of_steps > 0, ( - f"number_of_steps needs to be positive integer, your input {number_of_steps}" - ) + assert ( + isinstance(number_of_steps, int) and number_of_steps > 0 + ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" if number_of_steps == 1: return 1 previous, current = 1, 1 diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index efab6dacff3f..372dd2c74a71 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]: """ - assert isinstance(mask, int) and mask > 0, ( - f"mask needs to be positive integer, your input {mask}" - ) + assert ( + isinstance(mask, int) and mask > 0 + ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed diff --git a/financial/time_and_half_pay.py b/financial/time_and_half_pay.py index c5dff1bc1ce1..3e35c373a4e1 100644 --- a/financial/time_and_half_pay.py +++ b/financial/time_and_half_pay.py @@ -17,15 +17,15 @@ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: 10.0 """ # Check that all input parameters are float or integer - assert isinstance(hours_worked, (float, int)), ( - "Parameter 'hours_worked' must be of type 'int' or 'float'" - ) - assert isinstance(pay_rate, (float, int)), ( - "Parameter 'pay_rate' must be of type 'int' or 'float'" - ) - assert isinstance(hours, (float, int)), ( - "Parameter 'hours' must be of type 'int' or 'float'" - ) + assert isinstance( + hours_worked, (float, int) + ), "Parameter 'hours_worked' must be of type 'int' or 'float'" + assert isinstance( + pay_rate, (float, int) + ), "Parameter 'pay_rate' must be of type 'int' or 'float'" + assert isinstance( + hours, (float, int) + ), "Parameter 'hours' must be of type 'int' or 'float'" normal_pay = hours_worked * pay_rate over_time = max(0, hours_worked - hours) diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index 5209c152013e..612a31c4653c 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -11,14 +11,8 @@ import pytest -from .lib import ( - Matrix, - Vector, - axpy, - square_zero_matrix, - unit_basis_vector, - zero_vector, -) +from .lib import (Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, + zero_vector) class Test(unittest.TestCase): diff --git a/maths/numerical_analysis/integration_by_simpson_approx.py b/maths/numerical_analysis/integration_by_simpson_approx.py index 043f3a9a72af..934299997aac 100644 --- a/maths/numerical_analysis/integration_by_simpson_approx.py +++ b/maths/numerical_analysis/integration_by_simpson_approx.py @@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo AssertionError: precision should be positive integer your input : -1 """ - assert callable(function), ( - f"the function(object) passed should be callable your input : {function}" - ) + assert callable( + function + ), f"the function(object) passed should be callable your input : {function}" assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" - assert isinstance(precision, int) and precision > 0, ( - f"precision should be positive integer your input : {precision}" - ) + assert ( + isinstance(precision, int) and precision > 0 + ), f"precision should be positive integer your input : {precision}" # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function diff --git a/maths/prime_check.py b/maths/prime_check.py index a757c4108f24..f1bc4def2469 100644 --- a/maths/prime_check.py +++ b/maths/prime_check.py @@ -73,12 +73,12 @@ def test_primes(self): def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) - assert not is_prime(0), ( - "Zero doesn't have any positive factors, primes must have exactly two." - ) - assert not is_prime(1), ( - "One only has 1 positive factor, primes must have exactly two." - ) + assert not is_prime( + 0 + ), "Zero doesn't have any positive factors, primes must have exactly two." + assert not is_prime( + 1 + ), "One only has 1 positive factor, primes must have exactly two." assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) diff --git a/maths/primelib.py b/maths/primelib.py index 9f031efc50a9..c41aa07e09c4 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -66,9 +66,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and positive" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and positive" status = True @@ -254,9 +254,9 @@ def greatest_prime_factor(number): """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and >= 0" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and >= 0" ans = 0 @@ -296,9 +296,9 @@ def smallest_prime_factor(number): """ # precondition - assert isinstance(number, int) and (number >= 0), ( - "'number' must been an int and >= 0" - ) + assert isinstance(number, int) and ( + number >= 0 + ), "'number' must been an int and >= 0" ans = 0 @@ -399,9 +399,9 @@ def goldbach(number): """ # precondition - assert isinstance(number, int) and (number > 2) and is_even(number), ( - "'number' must been an int, even and > 2" - ) + assert ( + isinstance(number, int) and (number > 2) and is_even(number) + ), "'number' must been an int, even and > 2" ans = [] # this list will returned @@ -525,9 +525,9 @@ def kg_v(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and (ans >= 0), ( - "'ans' must been from type int and positive" - ) + assert isinstance(ans, int) and ( + ans >= 0 + ), "'ans' must been from type int and positive" return ans @@ -574,9 +574,9 @@ def get_prime(n): ans += 1 # precondition - assert isinstance(ans, int) and is_prime(ans), ( - "'ans' must been a prime number and from type int" - ) + assert isinstance(ans, int) and is_prime( + ans + ), "'ans' must been a prime number and from type int" return ans @@ -705,9 +705,9 @@ def is_perfect_number(number): """ # precondition - assert isinstance(number, int) and (number > 1), ( - "'number' must been an int and >= 1" - ) + assert isinstance(number, int) and ( + number > 1 + ), "'number' must been an int and >= 1" divisors = get_divisors(number) diff --git a/matrix/tests/test_matrix_operation.py b/matrix/tests/test_matrix_operation.py index 21ed7e371fd8..dde0f6e10f9e 100644 --- a/matrix/tests/test_matrix_operation.py +++ b/matrix/tests/test_matrix_operation.py @@ -7,7 +7,6 @@ """ import logging - # standard libraries import sys diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 3a8628f939f8..72debabb566a 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -160,9 +160,9 @@ def __init__( self._num_examples = 10000 self.one_hot = one_hot else: - assert images.shape[0] == labels.shape[0], ( - f"images.shape: {images.shape} labels.shape: {labels.shape}" - ) + assert ( + images.shape[0] == labels.shape[0] + ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] diff --git a/other/password.py b/other/password.py index dff1316c049c..ffc5ca83f2de 100644 --- a/other/password.py +++ b/other/password.py @@ -1,6 +1,7 @@ import secrets from random import shuffle -from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation +from string import (ascii_letters, ascii_lowercase, ascii_uppercase, digits, + punctuation) def password_generator(length: int = 8) -> str: diff --git a/quantum/q_fourier_transform.py b/quantum/q_fourier_transform.py index 762ac408190e..b1ac4dfa2c71 100644 --- a/quantum/q_fourier_transform.py +++ b/quantum/q_fourier_transform.py @@ -15,7 +15,8 @@ import numpy as np import qiskit -from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute +from qiskit import (Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, + execute) def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: diff --git a/quantum/quantum_teleportation.py.DISABLED.txt b/quantum/quantum_teleportation.py.DISABLED.txt index 5da79ed20183..f57be19685ad 100644 --- a/quantum/quantum_teleportation.py.DISABLED.txt +++ b/quantum/quantum_teleportation.py.DISABLED.txt @@ -12,7 +12,8 @@ https://qiskit.org/textbook/ch-algorithms/teleportation.html import numpy as np import qiskit -from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute +from qiskit import (Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, + execute) def quantum_teleportation( diff --git a/scripts/validate_solutions.py b/scripts/validate_solutions.py index f426153b5683..79a2f790081f 100755 --- a/scripts/validate_solutions.py +++ b/scripts/validate_solutions.py @@ -103,6 +103,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None: solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() - assert answer == expected, ( - f"Expected solution to {problem_number} to have hash {expected}, got {answer}" - ) + assert ( + answer == expected + ), f"Expected solution to {problem_number} to have hash {expected}, got {answer}" diff --git a/strings/string_to_num.py b/strings/string_to_num.py index 710683273067..1e7012f371ae 100644 --- a/strings/string_to_num.py +++ b/strings/string_to_num.py @@ -67,7 +67,7 @@ def to_int(word: str) -> int: "ninety": 90, } - multiplyers = { + multipliers = { "hundred": 100, "thousand": 1_000, "lakh": 1_00_000, @@ -97,7 +97,7 @@ def to_int(word: str) -> int: elif word in tens: temp += tens[word] else: - temp += multiplyers[word] + temp += multipliers[word] elif index == (len(words) - 1): if word in units: temp += units[word] @@ -106,14 +106,14 @@ def to_int(word: str) -> int: temp += tens[word] number += temp else: - temp *= multiplyers[word] + temp *= multipliers[word] number += temp elif word in units: temp += units[word] elif word in tens: temp += tens[word] - elif word in multiplyers: - temp *= multiplyers[word] + elif word in multipliers: + temp *= multipliers[word] number += temp temp = 0 From 3237b53eee0cfce393ffa58bb0f0895c1e78939e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Oct 2025 14:37:27 +0000 Subject: [PATCH 10/15] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- ciphers/base64_cipher.py | 12 +++--- computer_vision/cnn_classification.py | 1 + .../hashing/number_theory/prime_numbers.py | 6 +-- data_structures/heap/min_heap.py | 6 +-- .../kd_tree/example/example_usage.py | 3 +- data_structures/kd_tree/tests/test_kdtree.py | 15 ++++--- .../suffix_tree/tests/test_suffix_tree.py | 24 +++++------ .../filters/gabor_filter.py | 9 ++-- .../filters/laplacian_filter.py | 12 +++++- dynamic_programming/climbing_stairs.py | 6 +-- .../iterating_through_submasks.py | 6 +-- financial/time_and_half_pay.py | 18 ++++---- linear_algebra/src/test_linear_algebra.py | 10 ++++- .../integration_by_simpson_approx.py | 12 +++--- maths/prime_check.py | 12 +++--- maths/primelib.py | 42 +++++++++---------- matrix/tests/test_matrix_operation.py | 1 + neural_network/input_data.py | 6 +-- other/password.py | 3 +- quantum/q_fourier_transform.py | 3 +- scripts/validate_solutions.py | 6 +-- 21 files changed, 112 insertions(+), 101 deletions(-) diff --git a/ciphers/base64_cipher.py b/ciphers/base64_cipher.py index 2b950b1be37d..038d13963d95 100644 --- a/ciphers/base64_cipher.py +++ b/ciphers/base64_cipher.py @@ -105,13 +105,13 @@ def base64_decode(encoded_data: str) -> bytes: # Check if the encoded string contains non base64 characters if padding: - assert all( - char in B64_CHARSET for char in encoded_data[:-padding] - ), "Invalid base64 character(s) found." + assert all(char in B64_CHARSET for char in encoded_data[:-padding]), ( + "Invalid base64 character(s) found." + ) else: - assert all( - char in B64_CHARSET for char in encoded_data - ), "Invalid base64 character(s) found." + assert all(char in B64_CHARSET for char in encoded_data), ( + "Invalid base64 character(s) found." + ) # Check the padding assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding" diff --git a/computer_vision/cnn_classification.py b/computer_vision/cnn_classification.py index 5d02ee70b4f6..115333eba0d1 100644 --- a/computer_vision/cnn_classification.py +++ b/computer_vision/cnn_classification.py @@ -22,6 +22,7 @@ # Part 1 - Building the CNN import numpy as np + # Importing the Keras libraries and packages import tensorflow as tf from keras import layers, models diff --git a/data_structures/hashing/number_theory/prime_numbers.py b/data_structures/hashing/number_theory/prime_numbers.py index 2549a1477b2b..82071b5e9f09 100644 --- a/data_structures/hashing/number_theory/prime_numbers.py +++ b/data_structures/hashing/number_theory/prime_numbers.py @@ -32,9 +32,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and positive" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and positive" + ) if 1 < number < 4: # 2 and 3 are primes diff --git a/data_structures/heap/min_heap.py b/data_structures/heap/min_heap.py index ce7ed570a58d..577b98d788a1 100644 --- a/data_structures/heap/min_heap.py +++ b/data_structures/heap/min_heap.py @@ -124,9 +124,9 @@ def is_empty(self): return len(self.heap) == 0 def decrease_key(self, node, new_value): - assert ( - self.heap[self.idx_of_element[node]].val > new_value - ), "newValue must be less that current value" + assert self.heap[self.idx_of_element[node]].val > new_value, ( + "newValue must be less that current value" + ) node.val = new_value self.heap_dict[node.name] = new_value self.sift_up(self.idx_of_element[node]) diff --git a/data_structures/kd_tree/example/example_usage.py b/data_structures/kd_tree/example/example_usage.py index ec85d8d3183a..892c3b8c4a2a 100644 --- a/data_structures/kd_tree/example/example_usage.py +++ b/data_structures/kd_tree/example/example_usage.py @@ -10,8 +10,7 @@ from data_structures.kd_tree.build_kdtree import build_kdtree from data_structures.kd_tree.example.hypercube_points import hypercube_points -from data_structures.kd_tree.nearest_neighbour_search import \ - nearest_neighbour_search +from data_structures.kd_tree.nearest_neighbour_search import nearest_neighbour_search def main() -> None: diff --git a/data_structures/kd_tree/tests/test_kdtree.py b/data_structures/kd_tree/tests/test_kdtree.py index e882b0426296..d6a4a66dd24d 100644 --- a/data_structures/kd_tree/tests/test_kdtree.py +++ b/data_structures/kd_tree/tests/test_kdtree.py @@ -12,8 +12,7 @@ from data_structures.kd_tree.build_kdtree import build_kdtree from data_structures.kd_tree.example.hypercube_points import hypercube_points from data_structures.kd_tree.kd_node import KDNode -from data_structures.kd_tree.nearest_neighbour_search import \ - nearest_neighbour_search +from data_structures.kd_tree.nearest_neighbour_search import nearest_neighbour_search @pytest.mark.parametrize( @@ -49,14 +48,14 @@ def test_build_kdtree(num_points, cube_size, num_dimensions, depth, expected_res assert kdtree is not None, "Expected a KDNode, got None" # Check if root has correct dimensions - assert ( - len(kdtree.point) == num_dimensions - ), f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" + assert len(kdtree.point) == num_dimensions, ( + f"Expected point dimension {num_dimensions}, got {len(kdtree.point)}" + ) # Check that the tree is balanced to some extent (simplistic check) - assert isinstance( - kdtree, KDNode - ), f"Expected KDNode instance, got {type(kdtree)}" + assert isinstance(kdtree, KDNode), ( + f"Expected KDNode instance, got {type(kdtree)}" + ) def test_nearest_neighbour_search(): diff --git a/data_structures/suffix_tree/tests/test_suffix_tree.py b/data_structures/suffix_tree/tests/test_suffix_tree.py index 45c6790ac48a..c9dbe199d19d 100644 --- a/data_structures/suffix_tree/tests/test_suffix_tree.py +++ b/data_structures/suffix_tree/tests/test_suffix_tree.py @@ -22,18 +22,18 @@ def test_search_existing_patterns(self) -> None: patterns = ["ana", "ban", "na"] for pattern in patterns: with self.subTest(pattern=pattern): - assert self.suffix_tree.search( - pattern - ), f"Pattern '{pattern}' should be found." + assert self.suffix_tree.search(pattern), ( + f"Pattern '{pattern}' should be found." + ) def test_search_non_existing_patterns(self) -> None: """Test searching for patterns that do not exist in the suffix tree.""" patterns = ["xyz", "apple", "cat"] for pattern in patterns: with self.subTest(pattern=pattern): - assert not self.suffix_tree.search( - pattern - ), f"Pattern '{pattern}' should not be found." + assert not self.suffix_tree.search(pattern), ( + f"Pattern '{pattern}' should not be found." + ) def test_search_empty_pattern(self) -> None: """Test searching for an empty pattern.""" @@ -41,18 +41,18 @@ def test_search_empty_pattern(self) -> None: def test_search_full_text(self) -> None: """Test searching for the full text.""" - assert self.suffix_tree.search( - self.text - ), "The full text should be found in the suffix tree." + assert self.suffix_tree.search(self.text), ( + "The full text should be found in the suffix tree." + ) def test_search_substrings(self) -> None: """Test searching for substrings of the full text.""" substrings = ["ban", "ana", "a", "na"] for substring in substrings: with self.subTest(substring=substring): - assert self.suffix_tree.search( - substring - ), f"Substring '{substring}' should be found." + assert self.suffix_tree.search(substring), ( + f"Substring '{substring}' should be found." + ) if __name__ == "__main__": diff --git a/digital_image_processing/filters/gabor_filter.py b/digital_image_processing/filters/gabor_filter.py index 954997b894c8..aaec567f4c99 100644 --- a/digital_image_processing/filters/gabor_filter.py +++ b/digital_image_processing/filters/gabor_filter.py @@ -1,8 +1,7 @@ # Implementation of the Gaborfilter # https://en.wikipedia.org/wiki/Gabor_filter import numpy as np -from cv2 import (COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, - waitKey) +from cv2 import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filter2D, imread, imshow, waitKey def gabor_filter_kernel( @@ -49,9 +48,9 @@ def gabor_filter_kernel( _y = -sin_theta * px + cos_theta * py # fill kernel - gabor[y, x] = np.exp( - -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) - ) * np.cos(2 * np.pi * _x / lambd + psi) + gabor[y, x] = np.exp(-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2)) * np.cos( + 2 * np.pi * _x / lambd + psi + ) return gabor diff --git a/digital_image_processing/filters/laplacian_filter.py b/digital_image_processing/filters/laplacian_filter.py index d5b88ae5a98d..69b9616e4d30 100644 --- a/digital_image_processing/filters/laplacian_filter.py +++ b/digital_image_processing/filters/laplacian_filter.py @@ -3,8 +3,16 @@ # @Date : 10/04/2023 import numpy as np -from cv2 import (BORDER_DEFAULT, COLOR_BGR2GRAY, CV_64F, cvtColor, filter2D, - imread, imshow, waitKey) +from cv2 import ( + BORDER_DEFAULT, + COLOR_BGR2GRAY, + CV_64F, + cvtColor, + filter2D, + imread, + imshow, + waitKey, +) from digital_image_processing.filters.gaussian_filter import gaussian_filter diff --git a/dynamic_programming/climbing_stairs.py b/dynamic_programming/climbing_stairs.py index d6273d025f08..38bdb427eedc 100644 --- a/dynamic_programming/climbing_stairs.py +++ b/dynamic_programming/climbing_stairs.py @@ -25,9 +25,9 @@ def climb_stairs(number_of_steps: int) -> int: ... AssertionError: number_of_steps needs to be positive integer, your input -7 """ - assert ( - isinstance(number_of_steps, int) and number_of_steps > 0 - ), f"number_of_steps needs to be positive integer, your input {number_of_steps}" + assert isinstance(number_of_steps, int) and number_of_steps > 0, ( + f"number_of_steps needs to be positive integer, your input {number_of_steps}" + ) if number_of_steps == 1: return 1 previous, current = 1, 1 diff --git a/dynamic_programming/iterating_through_submasks.py b/dynamic_programming/iterating_through_submasks.py index 372dd2c74a71..efab6dacff3f 100644 --- a/dynamic_programming/iterating_through_submasks.py +++ b/dynamic_programming/iterating_through_submasks.py @@ -37,9 +37,9 @@ def list_of_submasks(mask: int) -> list[int]: """ - assert ( - isinstance(mask, int) and mask > 0 - ), f"mask needs to be positive integer, your input {mask}" + assert isinstance(mask, int) and mask > 0, ( + f"mask needs to be positive integer, your input {mask}" + ) """ first submask iterated will be mask itself then operation will be performed diff --git a/financial/time_and_half_pay.py b/financial/time_and_half_pay.py index 3e35c373a4e1..c5dff1bc1ce1 100644 --- a/financial/time_and_half_pay.py +++ b/financial/time_and_half_pay.py @@ -17,15 +17,15 @@ def pay(hours_worked: float, pay_rate: float, hours: float = 40) -> float: 10.0 """ # Check that all input parameters are float or integer - assert isinstance( - hours_worked, (float, int) - ), "Parameter 'hours_worked' must be of type 'int' or 'float'" - assert isinstance( - pay_rate, (float, int) - ), "Parameter 'pay_rate' must be of type 'int' or 'float'" - assert isinstance( - hours, (float, int) - ), "Parameter 'hours' must be of type 'int' or 'float'" + assert isinstance(hours_worked, (float, int)), ( + "Parameter 'hours_worked' must be of type 'int' or 'float'" + ) + assert isinstance(pay_rate, (float, int)), ( + "Parameter 'pay_rate' must be of type 'int' or 'float'" + ) + assert isinstance(hours, (float, int)), ( + "Parameter 'hours' must be of type 'int' or 'float'" + ) normal_pay = hours_worked * pay_rate over_time = max(0, hours_worked - hours) diff --git a/linear_algebra/src/test_linear_algebra.py b/linear_algebra/src/test_linear_algebra.py index 612a31c4653c..5209c152013e 100644 --- a/linear_algebra/src/test_linear_algebra.py +++ b/linear_algebra/src/test_linear_algebra.py @@ -11,8 +11,14 @@ import pytest -from .lib import (Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, - zero_vector) +from .lib import ( + Matrix, + Vector, + axpy, + square_zero_matrix, + unit_basis_vector, + zero_vector, +) class Test(unittest.TestCase): diff --git a/maths/numerical_analysis/integration_by_simpson_approx.py b/maths/numerical_analysis/integration_by_simpson_approx.py index 934299997aac..043f3a9a72af 100644 --- a/maths/numerical_analysis/integration_by_simpson_approx.py +++ b/maths/numerical_analysis/integration_by_simpson_approx.py @@ -88,18 +88,18 @@ def simpson_integration(function, a: float, b: float, precision: int = 4) -> flo AssertionError: precision should be positive integer your input : -1 """ - assert callable( - function - ), f"the function(object) passed should be callable your input : {function}" + assert callable(function), ( + f"the function(object) passed should be callable your input : {function}" + ) assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}" assert isinstance(function(a), (float, int)), ( "the function should return integer or float return type of your function, " f"{type(a)}" ) assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}" - assert ( - isinstance(precision, int) and precision > 0 - ), f"precision should be positive integer your input : {precision}" + assert isinstance(precision, int) and precision > 0, ( + f"precision should be positive integer your input : {precision}" + ) # just applying the formula of simpson for approximate integration written in # mentioned article in first comment of this file and above this function diff --git a/maths/prime_check.py b/maths/prime_check.py index f1bc4def2469..a757c4108f24 100644 --- a/maths/prime_check.py +++ b/maths/prime_check.py @@ -73,12 +73,12 @@ def test_primes(self): def test_not_primes(self): with pytest.raises(ValueError): is_prime(-19) - assert not is_prime( - 0 - ), "Zero doesn't have any positive factors, primes must have exactly two." - assert not is_prime( - 1 - ), "One only has 1 positive factor, primes must have exactly two." + assert not is_prime(0), ( + "Zero doesn't have any positive factors, primes must have exactly two." + ) + assert not is_prime(1), ( + "One only has 1 positive factor, primes must have exactly two." + ) assert not is_prime(2 * 2) assert not is_prime(2 * 3) assert not is_prime(3 * 3) diff --git a/maths/primelib.py b/maths/primelib.py index c41aa07e09c4..9f031efc50a9 100644 --- a/maths/primelib.py +++ b/maths/primelib.py @@ -66,9 +66,9 @@ def is_prime(number: int) -> bool: """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and positive" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and positive" + ) status = True @@ -254,9 +254,9 @@ def greatest_prime_factor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and >= 0" + ) ans = 0 @@ -296,9 +296,9 @@ def smallest_prime_factor(number): """ # precondition - assert isinstance(number, int) and ( - number >= 0 - ), "'number' must been an int and >= 0" + assert isinstance(number, int) and (number >= 0), ( + "'number' must been an int and >= 0" + ) ans = 0 @@ -399,9 +399,9 @@ def goldbach(number): """ # precondition - assert ( - isinstance(number, int) and (number > 2) and is_even(number) - ), "'number' must been an int, even and > 2" + assert isinstance(number, int) and (number > 2) and is_even(number), ( + "'number' must been an int, even and > 2" + ) ans = [] # this list will returned @@ -525,9 +525,9 @@ def kg_v(number1, number2): done.append(n) # precondition - assert isinstance(ans, int) and ( - ans >= 0 - ), "'ans' must been from type int and positive" + assert isinstance(ans, int) and (ans >= 0), ( + "'ans' must been from type int and positive" + ) return ans @@ -574,9 +574,9 @@ def get_prime(n): ans += 1 # precondition - assert isinstance(ans, int) and is_prime( - ans - ), "'ans' must been a prime number and from type int" + assert isinstance(ans, int) and is_prime(ans), ( + "'ans' must been a prime number and from type int" + ) return ans @@ -705,9 +705,9 @@ def is_perfect_number(number): """ # precondition - assert isinstance(number, int) and ( - number > 1 - ), "'number' must been an int and >= 1" + assert isinstance(number, int) and (number > 1), ( + "'number' must been an int and >= 1" + ) divisors = get_divisors(number) diff --git a/matrix/tests/test_matrix_operation.py b/matrix/tests/test_matrix_operation.py index dde0f6e10f9e..21ed7e371fd8 100644 --- a/matrix/tests/test_matrix_operation.py +++ b/matrix/tests/test_matrix_operation.py @@ -7,6 +7,7 @@ """ import logging + # standard libraries import sys diff --git a/neural_network/input_data.py b/neural_network/input_data.py index 72debabb566a..3a8628f939f8 100644 --- a/neural_network/input_data.py +++ b/neural_network/input_data.py @@ -160,9 +160,9 @@ def __init__( self._num_examples = 10000 self.one_hot = one_hot else: - assert ( - images.shape[0] == labels.shape[0] - ), f"images.shape: {images.shape} labels.shape: {labels.shape}" + assert images.shape[0] == labels.shape[0], ( + f"images.shape: {images.shape} labels.shape: {labels.shape}" + ) self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] diff --git a/other/password.py b/other/password.py index ffc5ca83f2de..dff1316c049c 100644 --- a/other/password.py +++ b/other/password.py @@ -1,7 +1,6 @@ import secrets from random import shuffle -from string import (ascii_letters, ascii_lowercase, ascii_uppercase, digits, - punctuation) +from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: diff --git a/quantum/q_fourier_transform.py b/quantum/q_fourier_transform.py index b1ac4dfa2c71..762ac408190e 100644 --- a/quantum/q_fourier_transform.py +++ b/quantum/q_fourier_transform.py @@ -15,8 +15,7 @@ import numpy as np import qiskit -from qiskit import (Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, - execute) +from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_fourier_transform(number_of_qubits: int = 3) -> qiskit.result.counts.Counts: diff --git a/scripts/validate_solutions.py b/scripts/validate_solutions.py index 79a2f790081f..f426153b5683 100755 --- a/scripts/validate_solutions.py +++ b/scripts/validate_solutions.py @@ -103,6 +103,6 @@ def test_project_euler(solution_path: pathlib.Path) -> None: solution_module = convert_path_to_module(solution_path) answer = str(solution_module.solution()) answer = hashlib.sha256(answer.encode()).hexdigest() - assert ( - answer == expected - ), f"Expected solution to {problem_number} to have hash {expected}, got {answer}" + assert answer == expected, ( + f"Expected solution to {problem_number} to have hash {expected}, got {answer}" + ) From 98c90fd616378c630d9bee2f884e8e5e1a8294ba Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 20:53:37 +0530 Subject: [PATCH 11/15] Add string to number converter --- sorts/bead_sort.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 8335eb2cef36..89cf6a6c304e 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -32,13 +32,13 @@ def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") - for i, (rod_upper, rod_lower) in enumerate(pairwise(sequence)): - if rod_upper > rod_lower: - sequence[i] -= rod_upper - rod_lower - sequence[i + 1] += rod_upper - rod_lower + for _ in range(len(sequence)): + for i, (rod_upper, rod_lower) in enumerate(pairwise(sequence)): + if rod_upper > rod_lower: + sequence[i] -= rod_upper - rod_lower + sequence[i + 1] += rod_upper - rod_lower return sequence - if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9] From 48346429f42751715a0c8cac6dab550486d5430d Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Oct 2025 15:24:05 +0000 Subject: [PATCH 12/15] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/bead_sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 89cf6a6c304e..a213c1b20172 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -39,6 +39,7 @@ def bead_sort(sequence: list) -> list: sequence[i + 1] += rod_upper - rod_lower return sequence + if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9] From dc208b625a94f178ca2b009d668878c2139e85a7 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 21:02:30 +0530 Subject: [PATCH 13/15] ruff error for bead check --- sorts/bead_sort.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index a213c1b20172..f6823a16275c 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -29,14 +29,12 @@ def bead_sort(sequence: list) -> list: TypeError: Sequence must be list of non-negative integers """ from itertools import pairwise - if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") - for _ in range(len(sequence)): - for i, (rod_upper, rod_lower) in enumerate(pairwise(sequence)): - if rod_upper > rod_lower: - sequence[i] -= rod_upper - rod_lower - sequence[i + 1] += rod_upper - rod_lower + for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): + if rod_upper > rod_lower: + sequence[i] -= rod_upper - rod_lower + sequence[i + 1] += rod_upper - rod_lower return sequence From 13f427a692684138fe6c20d5d620d4c043b20ce9 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Wed, 1 Oct 2025 15:34:41 +0000 Subject: [PATCH 14/15] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- sorts/bead_sort.py | 1 + 1 file changed, 1 insertion(+) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index f6823a16275c..177e3f26be68 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -29,6 +29,7 @@ def bead_sort(sequence: list) -> list: TypeError: Sequence must be list of non-negative integers """ from itertools import pairwise + if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): From 897ed83c94b7075aa2d3bab885984e5b6d0150f4 Mon Sep 17 00:00:00 2001 From: AryanJadhav15 Date: Wed, 1 Oct 2025 21:07:56 +0530 Subject: [PATCH 15/15] solve bead sort --- sorts/bead_sort.py | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/sorts/bead_sort.py b/sorts/bead_sort.py index 177e3f26be68..58b218225ced 100644 --- a/sorts/bead_sort.py +++ b/sorts/bead_sort.py @@ -3,9 +3,12 @@ https://en.wikipedia.org/wiki/Bead_sort """ +from itertools import pairwise def bead_sort(sequence: list) -> list: """ + Sorts a list of non-negative integers using bead sort. + >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] @@ -32,13 +35,29 @@ def bead_sort(sequence: list) -> list: if any(not isinstance(x, int) or x < 0 for x in sequence): raise TypeError("Sequence must be list of non-negative integers") - for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])): - if rod_upper > rod_lower: - sequence[i] -= rod_upper - rod_lower - sequence[i + 1] += rod_upper - rod_lower - return sequence + + # Early return for empty list + if not sequence: + return [] + + max_value = max(sequence) + beads = [[0] * len(sequence) for _ in range(max_value)] + + # Drop beads + for i, num in enumerate(sequence): + for j in range(num): + beads[j][i] = 1 + + # Let beads "fall" + for row in beads: + count = sum(row) + for i in range(len(row)): + row[i] = 1 if i < count else 0 + + # Read off sorted sequence + return [sum(beads[j][i] for j in range(max_value)) for i in range(len(sequence))] if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] - assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9] + assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9] \ No newline at end of file