python allows conversions from string to integer using any base in the range [2,36] using:
int(string,base)
im looking for an elegant inver
Here's my solution:
def int2base(a, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
baseit = lambda a=a, b=base: (not a) and numerals[0] or baseit(a-a%b,b*base)+numerals[a%b%(base-1) or (a%b) and (base-1)]
return baseit()
In any base, every number is equal to a1+a2*base**2+a3*base**3.... The "mission" is to find all a's.
For every N=1,2,3..., the code is isolating the aN*base**N by "mouduling" by b for b=base**(N+1) which slice all a's bigger than N, and slicing all the a's that their serial is smaller than N by decreasing a every time the function is called by the current aN*base**N.
Base%(base-1)==1 therefore base**p%(base-1)==1 and therefore q*base^p%(base-1)==q with only one exception when q=base-1 which returns 0.
To fix that, in case it returns 0, the function is checking is it 0 from the beginning.
In this sample, there is only one multiplication (instead of division) and some instances of modulus which take relatively small amounts of time.