Search code examples
pythonalgorithmbinaryhexoctal

Python Morphology n_ary_converter


Other than just binary and decimal, we can have numbers of any base. Common bases that we work with include octal, hexadecimal and base64.

Here is a table of numbers from 0 to 15 in each of the above mentioned bases except base64.

http://www.themathwebsite.com/TogglerNumbers/Octal.GIF

QUESTION: Write a function make_decimal_to_n_ary_converter that accepts a number n where 1 < n < 17, and returns a number converter that converts a given decimal number into that of base n.

def make_decimal_to_n_ary_converter(n):
    # return a number converter that takes a decimal number 
    # and returns its string representation in base n
    def converter(x):
        if n == 2:
            return bin(x)[2:]
        elif n == 8:
            return oct(x)[2:]
        elif n == 16:
            return hex(x)[2:].upper()
    return converter

Essentially, this code only works for binary, octal and hexadecimal, but i need to write it programatically without the python in-built function to allow it to run from n_ary 1-17

Here's an example of how the binary conversion is written programatically:

def decimal_to_binary(n):
    # return bin(n)[2:]
    if n == 0:
        return '0'
    binary = ''
    while n > 0:
        binary += '0' if n % 2 == 0 else '1'
        n = n//2
    return binary[::-1]

Solution

  • Your line binary += '0' if n % 2 == 0 else '1' isn't really necessary in my opinion. binary += n % 2 would suffice.

    First we have to define the digit set. Since we know that base will be less than 17 I have taken a 17 digit set (digit_list). For a given base k, digit_list[k] will be our available digits. The rest of the function is the same. we append basek_num with the corr. value in digit_list of n%k. until our number is 0.

    def decimal_to_basek(n, k):
        # return bin(n)[2:]
        digit_list = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g',]
        if n == 0:
            return '0'
        basek_num = ''
        while n > 0:
            basek_num +=  digit_list[n % k]
            n = n//k
        return basek_num[::-1]