tomislav-b
7/9/2014 - 3:58 PM

For a given number and its radix, returns the corresponding decimal number. Works for radix range of 1 < radix < 36.

For a given number and its radix, returns the corresponding decimal number. Works for radix range of 1 < radix < 36.

numeralValues = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, 
					"6": 6, "7": 7, "8": 8, "9": 9, "A": 10, "B": 11,
					"C": 12, "D": 13, "E": 14, "F": 15, "G": 16, "H": 17,
					"I": 18, "J": 19, "K": 20, "L": 21, "M": 22, "N": 23,
					"O": 24, "P": 25, "Q": 26, "R": 27, "S": 28, "T": 29,
					"U": 30, "V": 31, "W": 32, "X": 33, "Y": 34, "Z": 35}

def to_decimal(str_number, radix):
    if not is_valid_combination(str_number, radix):
        return -1

    str_number = str_number[::-1]
    decimal_value = 0
    current_weight = 0

    # Calculate the weighted value of every digit and add it to the sum
    for digit in str_number:
        decimal_value += numeralValues[digit] * radix ** current_weight
        current_weight += 1

    return decimal_value


def is_valid_combination(str_number, radix):
    for digit in str_number:
        if numeralValues[digit] >= radix: # The digit can't be equal or greater than the radix
            return False

    return True