Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Number Base by colinmcnicholl
import string
def checkio(str_number, radix):
"""input: Two arguments. A number as string and a radix as an integer. The radix is less than 37 and greater
than 1. The task uses digits and the letters A-Z for the strings.
The function convert the number into decimal form.
output: The converted number as an integer."""
# Create a dictionary with keys as [0-9A-Z] and values [0-35]
uppercase_letters_list = list(string.ascii_uppercase)
digits = string.digits
zero_nine_list = list(range(10))
zero_nine_list_str = [str(elem) for elem in zero_nine_list]
L = zero_nine_list_str + uppercase_letters_list
num_list = list(range(36))
d = dict(zip(L, num_list))
# Loop over each element of the input number string and convert to value using dictionary.
number_list = list(str_number)
dec_list = []
for num in number_list:
dec = d[num]
dec_list.append(dec)
# Case when number cannot be converted
if radix <= max(dec_list):
return -1
# Case when number can be converted
else:
n = len(dec_list)
idx = 1
converted_number = 0
for dec in dec_list:
res = dec * radix ** (n - idx)
converted_number += res
idx += 1
return converted_number
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "Bin"
assert checkio("101", 5) == 26, "5 base"
assert checkio("Z", 36) == 35, "Z base"
assert checkio("AB", 10) == -1, "B > A = 10"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
Sept. 13, 2017