|
| 1 | +""" |
| 2 | +Convert a sequence of digits in one base, representing a number, |
| 3 | +into a sequence of digits in another base, representing the same number. |
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def rebase(input_base: int, digits: list[int], output_base: int) -> list[int]: |
| 8 | + """ |
| 9 | + Convert a non-negative integer represented as digits in one base |
| 10 | + to digits in another base. |
| 11 | +
|
| 12 | + :param int input_base: Base of the input digits; must be >= 2. |
| 13 | + :param list[int] digits: Sequence of digits where each d satisfies |
| 14 | + 0 <= d < input_base. Leading zeros are allowed; |
| 15 | + an empty list denotes 0. |
| 16 | + :param int output_base: Base for the output digits; must be >= 2. |
| 17 | + :returns: Digits of the same number in ``output_base``, without leading |
| 18 | + zeros (except ``[0]`` for zero). |
| 19 | + :rtype: list[int] |
| 20 | + :raises ValueError: If ``input_base < 2``, if any digit violates |
| 21 | + ``0 <= d < input_base``, or if ``output_base < 2``. |
| 22 | + """ |
| 23 | + # Step 1: Validate the Inputs (Before Any Calculations) |
| 24 | + # Validate input_base >= 2 |
| 25 | + if input_base < 2: |
| 26 | + raise ValueError("input base must be >= 2") |
| 27 | + |
| 28 | + # Validate each digit is 0 <= d < input_base |
| 29 | + for d in digits: |
| 30 | + if not 0 <= d < input_base: |
| 31 | + raise ValueError("all digits must satisfy 0 <= d < input base") |
| 32 | + |
| 33 | + # Validate output_base >= 2 |
| 34 | + if output_base < 2: |
| 35 | + raise ValueError("output base must be >= 2") |
| 36 | + |
| 37 | + # Step 2: Calculate the Intermediate Value Using input_base and digits |
| 38 | + # Start from the least significant number (from the right) |
| 39 | + # -> hence reverse the list |
| 40 | + intermediate_val: int = sum( |
| 41 | + digit * (input_base**i) for i, digit in enumerate(reversed(digits)) |
| 42 | + ) |
| 43 | + |
| 44 | + # Step 3: Convert the Intermediate Value to digits in output_base |
| 45 | + answer: list[int] = [] |
| 46 | + while True: |
| 47 | + # Compute quotient (new intermediate_val) |
| 48 | + # and remainder (least significant digit) |
| 49 | + intermediate_val, remainder = ( |
| 50 | + intermediate_val // output_base, |
| 51 | + intermediate_val % output_base, |
| 52 | + ) |
| 53 | + # Add the least significant number into a new list of digits |
| 54 | + answer.append(remainder) |
| 55 | + # Break the loop since reach zero, no more calculation needed |
| 56 | + if intermediate_val == 0: |
| 57 | + break |
| 58 | + |
| 59 | + # Reverse the list to place the most significant digit first (leftmost). |
| 60 | + return answer[::-1] |
0 commit comments