[Python] Checkio Solution 解答 – Number Base

架網編程

Problem:

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.

 

Level:

Elementary

 

Input:

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

 

Output:

The converted number as an integer.

 

Precondition:

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)

Comment:

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.

發佈日期:2017年9月23日 | 作者:橘小佑

Copyright © Vantopics