Created
December 30, 2017 15:38
-
-
Save py-in-the-sky/d8c920fe041506a61eea9f87894e6c4a to your computer and use it in GitHub Desktop.
Convert a number from base 10 to another base.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Written after seeing a similar program in the MIT/EDX course | |
Advanced Software Construction in Java. | |
""" | |
def convert(n, base): | |
assert 2 <= base <= 16 | |
if n == 0: | |
return "0" | |
elif n < 0: | |
return "-" + _convert(-n, base) | |
else: | |
return _convert(n, base) | |
def _convert(n, base): | |
result = [] | |
while n > 0: | |
leftmost_digit = "0123456789abcdef"[n%base] | |
result.append(leftmost_digit) | |
n /= base | |
return "".join(reversed(result)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment