Search code examples
pythonpython-3.xindexing

How can I convert base 10 integers to base 80 in Python without encountering IndexError?


I'm working on a Python script where I need to convert base 10 integers to base 80 using a specific set of characters. I've implemented a function for this purpose, but I keep encountering an IndexError due to the index going out of range. Here's the function I'm using:

def base10_to_base80(n):
    base_80 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~!$&\'()*+,:;=/'  # Corrected string
    if n == 0:
        return base_80[0]
    digits = []
    while n:
        digits.append(base_80[n % 80])
        n //= 80
    return ''.join(digits[::-1])

# Example usage:
decimal_number = 79
base_80_number = base10_to_base80(decimal_number)
print(base_80_number)

Solution

  • You are getting this error because

    base_80 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~!$&\'()*+,:;=/
    

    len(base_80) is 79

    you need one more character in base_80 to make it work properly.



    Your current code will work for base 79 you can just modify:

    digits.append(base_80[n % 79])
            n //= 79
    

    your code will work good.