Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Try/except is your friend too. solution in Clear category for Number Base by tigercat2000
def checkio(str_number, radix):
# int() will throw a ValueError if it cannot convert a base correctly.
# So, we use a try/except statement to successfully return `-1`.
try:
# Convert the string into the integer, using the second argument as the radix.
n = int(str_number, radix)
except ValueError:
# Uh-oh, we got a ValueError. Return -1, this can't be converted.
return -1
# No ValueError, return the successfully converted number.
return n
#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"
Nov. 5, 2016
Comments: