In Python, the int() function effortlessly creates an integer from a string with a specified base. However, the inverse operation of converting an integer to a string can be tricky. We aim to develop a general solution, int2base(num, base), that fulfills the condition:
int(int2base(x, b), b) == x
Here's a surprisingly simple solution that handles arbitrary bases:
def numberToBase(n, b): if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1]
This function converts a number n to base b and returns a list of digits. To convert a large number to base 577, for instance:
numberToBase(67854 ** 15 - 102, 577)
It will give you the correct result as a list:
[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]
The provided solution demonstrates that sometimes, custom functions are necessary when built-in functions lack desired functionality. Here, int2base() overcomes limitations by:
The above is the detailed content of How Can I Efficiently Convert Integers to Strings in Any Base in Python?. For more information, please follow other related articles on the PHP Chinese website!