[Python] Checkio Solution 解答 – Number Base



You are given a positive number as a string along with the radix for it. Your function should convert it into decimal form. The radix is less than 37 and greater than 1. The task uses digits and the letters A-Z for the strings.

Watch out for cases when the number cannot be converted. For example: "1A" cannot be converted with radix 9. For these cases your function should return -1.






Two arguments. A number as string and a radix as an integer.



The converted number as an integer.



re.match("\A[A-Z0-9]\Z", str_number)
0 < len(str_number) ≤ 10
2 ≤ radix ≤ 36


Source: https://py.checkio.org

My Solution:

def checkio(str_number, radix): 
  import string 
  letter = string.ascii_uppercase 
  num = string.digits 
  for ch in str_number: 
    if ch in letter: 
      if letter.index(ch) + 10 >= radix: 
        return -1 
      elif ch in num: 
        if int(ch) >= radix: 
          return -1 
  return int(str_number,radix)


Not that familiar with radix. I didn't know A = 10 for numeral systems. Luckily, Codecademy had a lesson about bitwise operators, which taught me that int() can actually help solve this kind of problem.

Copyright © Vantopics