Python elegant inverse function of int(string,base)

后端 未结 11 875
谎友^
谎友^ 2020-11-28 06:01

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

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 06:13

    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()
    

    Explanation

    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.


    Advantages

    In this sample, there is only one multiplication (instead of division) and some instances of modulus which take relatively small amounts of time.

提交回复
热议问题