Skip to content

Instantly share code, notes, and snippets.

@jpgoldberg
Created March 31, 2024 18:41
Show Gist options
  • Save jpgoldberg/5a9366ebfc97084411a83450950ff19a to your computer and use it in GitHub Desktop.
Save jpgoldberg/5a9366ebfc97084411a83450950ff19a to your computer and use it in GitHub Desktop.
Python integer base conversion (Quora answer)
# A less abstract version fo this was created for
# quora answer https://qr.ae/psY5cy
import pytest
from numbers import Number
def base_convert(x: int, radix: int) -> str:
symbols = '0123456789abcdefghijklmnopqrstuvwxyz'
if radix < 2 or radix > len(symbols):
raise ValueError(f"radix must be in [2, {len(symbols)}]")
if not isinstance(x, Number):
raise TypeError
if not isinstance(x, int):
raise NotImplementedError("Only handles int at the moment")
# some special cases
if x == 0:
return "0"
if x < 0:
return '-' + base_convert(-x, radix)
digits = []
while x > 0:
x, r = divmod(x, radix)
digits.append(symbols[r])
return ''.join(reversed(digits))
def base6(x: int) -> str:
return base_convert(x, 6)
def test_base6() -> None:
vectors = [
(6, "10"),
(0, "0"),
(5, "5"),
(35, "55"),
(36, "100"),
(37, "101"),
(71, "155"),
(-71, "-155"),
(-0, "0"),
]
for tv in vectors:
input, expected = tv
assert base6(input) == expected
if __name__ == '__main__':
status = pytest.main([__file__])
print(f'pytest status: {status}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment