py_number_base_converter — Convert Between Number Bases
Difficulty: medium
Write a function that converts a number from one base to another. Support bases from 2 to 36 inclusive, using digits 0-9 and letters A-Z for values 10-35. Return "ERROR" for invalid inputs (base, digits).
def number_base_converter(number: str, from_base: int, to_base: int) -> str:
Examples
>>> number_base_converter("1010", 2, 10)
"10"
>>> number_base_converter("FF", 16, 10)
"255"
>>> number_base_converter("255", 10, 16)
"FF"
>>> number_base_converter("123", 10, 2)
"1111011"
>>> number_base_converter("Z", 36, 10)
"35"
>>> number_base_converter("35", 10, 36)
"Z"
>>> number_base_converter("123", 1, 10)
"ERROR"
>>> number_base_converter("G", 16, 10)
"ERROR"
Solution
Download py_number_base_converter.pydef number_base_converter(number: str, from_base: int, to_base: int) -> str:
if not (2 <= from_base <= 36) or not (2 <= to_base <= 36):
return "ERROR"
if not number:
return "ERROR"
digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
value = 0
for ch in number.upper():
if ch not in digits:
return "ERROR"
d = digits.index(ch)
if d >= from_base:
return "ERROR"
value = value * from_base + d
if value == 0:
return "0"
result = ""
while value > 0:
result = digits[value % to_base] + result
value //= to_base
return result
How It Works
Goal: Convert a number string from one base to another, with validation.
Approach: Parse the input into an integer using the source base, then build the output string by repeatedly dividing by the target base.
Step by step:
- Validate both bases are within
[2, 36]; otherwise return"ERROR". - For each character of the input, find its digit value. Reject characters that are out of the digit alphabet or out of range for the source base.
- Accumulate the integer value:
value = value * from_base + digit. - Convert back by repeatedly taking
value % to_base(rightmost digit) and integer-dividing.
Key concept: Positional numeral systems — a number in base b is Σ dᵢ · bⁱ, so parsing multiplies by b and converting back divides by b.