Python elegant inverse function of int(string,base)

后端 未结 11 857
谎友^
谎友^ 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:12

    Looks like this might be my time to shine. Believe it or not, the following is some ported and modified Scratch code I wrote nearly three years ago to see just how quickly I could convert from denary to hexadecimal.

    Simply put, it works by first taking an integer, base, and an optional accompanying string of numerals, then calculating each digit of the converted integer beginning with the least significant.

    def int2base(num, base, abc="0123456789abcdefghijklmnopqrstuvwxyz"):
      if num < 0:
        return '-' + int2base(-num, base, abc)
    
      else:
        output = abc[num % base] # rightmost digit
    
        while num >= base:
          num //= base # move to next digit to the left
          output = abc[num % base] + output # this digit
    
        return output
    

    On my own PC, this code was able to complete 10 million iterations using the input range, 0-9999, and base, 36, in consistently below 5 seconds. Using the same test, I have found this to be at least 4 seconds faster than any other answer so far.

    >>> timeit.timeit(lambda: [int2base(n, 36) for n in range(10000)], number=1000)
    4.883068453882515
    

提交回复
热议问题