Skip to content

Instantly share code, notes, and snippets.

@un1t
Created April 6, 2016 18:56
Show Gist options
  • Save un1t/6253bb5b22ea79c06bf75b0c7ac8f14d to your computer and use it in GitHub Desktop.
Save un1t/6253bb5b22ea79c06bf75b0c7ac8f14d to your computer and use it in GitHub Desktop.
Converting an Integer to a String in Any Base
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