Created
April 6, 2016 18:56
-
-
Save un1t/6253bb5b22ea79c06bf75b0c7ac8f14d to your computer and use it in GitHub Desktop.
Converting an Integer to a String in Any Base
This file contains hidden or 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
import string | |
# http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsConvertinganIntegertoaStringinAnyBase.html | |
class AbcNumCoverter: | |
chars = string.digits + string.ascii_lowercase | |
base = len(chars) | |
@classmethod | |
def to_str(cls, n): | |
if n < cls.base: | |
return cls.chars[n] | |
else: | |
return cls.to_str(n // cls.base) + cls.chars[n % cls.base] | |
@classmethod | |
def to_num(cls, s): | |
n = 0 | |
for index, char in enumerate(s[::-1]): | |
n += cls.chars.index(char) * cls.base ** index | |
return n | |
for x in range(100): | |
s = AbcNumCoverter.to_str(x) | |
n = AbcNumCoverter.to_num(s) | |
print(x, s, n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment