From fe98a30bd1e3dce50982f66d276617887c26dbf8 Mon Sep 17 00:00:00 2001 From: Ewan John Dennis Date: Tue, 21 Apr 2026 10:17:28 +0530 Subject: [PATCH 1/2] Refactor binary to decimal conversion function Rewrote bin_to_decimal to use Python's built-in int(s, 2) instead of a manual loop that accumulates the decimal value digit by digit. The logic and doctests are unchanged. Also added a guard for "-" as input, which previously slipped past the empty-string check and raised an unhelpful ValueError about non-binary values. --- conversions/binary_to_decimal.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/conversions/binary_to_decimal.py b/conversions/binary_to_decimal.py index 914a9318c225..45797613e114 100644 --- a/conversions/binary_to_decimal.py +++ b/conversions/binary_to_decimal.py @@ -1,6 +1,6 @@ def bin_to_decimal(bin_string: str) -> int: """ - Convert a binary value to its decimal equivalent + Convert a binary value to its decimal equivalent. >>> bin_to_decimal("101") 5 @@ -24,20 +24,21 @@ def bin_to_decimal(bin_string: str) -> int: ValueError: Non-binary value was passed to the function """ bin_string = str(bin_string).strip() + if not bin_string: raise ValueError("Empty string was passed to the function") + is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] - if not all(char in "01" for char in bin_string): + + if not bin_string or not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") - decimal_number = 0 - for char in bin_string: - decimal_number = 2 * decimal_number + int(char) - return -decimal_number if is_negative else decimal_number + + result = int(bin_string, 2) + return -result if is_negative else result if __name__ == "__main__": from doctest import testmod - testmod() From f8618331d5be3c5b5a3a6db7cec64554a59eacbf Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 21 Apr 2026 04:49:16 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- conversions/binary_to_decimal.py | 1 + 1 file changed, 1 insertion(+) diff --git a/conversions/binary_to_decimal.py b/conversions/binary_to_decimal.py index 45797613e114..1cd150b02eae 100644 --- a/conversions/binary_to_decimal.py +++ b/conversions/binary_to_decimal.py @@ -41,4 +41,5 @@ def bin_to_decimal(bin_string: str) -> int: if __name__ == "__main__": from doctest import testmod + testmod()