PAT A1027:Colors in Mars(进制转换)

递归函数简单实现十进制向任意进制转换

题目内容

People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

Input Specification:

Each input file contains one test case which occupies a line containing the three decimal color values.

Output Specification:

For each test case you should output the Mars RGB value in the following format: first output #, then followed by a 6-digit number where all the English characters must be upper-cased. If a single color is only 1-digit long, you must print a 0 to its left.

Sample Input:

15 43 71

Sample Output:

#123456

题目要点

本题 20 分,考察了进制数的转换和输出结果添加前导零。前导零可以用 Python 强大的字符串格式输出实现。十进制向任意进制转换用的算法是“取余倒排法”,即将待求的数除以进制,取余,商部分继续除以进制,直到商为零,将所得余数倒序排列,得到目标进制的值。

AC 源代码

def radix(n, base):
    char = '0123456789ABC'
    if n < base:
        return char[n]
    else:
        return radix(n//base, base) + char[n % base]

r, g, b = map(lambda x: radix(int(x), 13), input().split())
print('#{:>02}{:>02}{:>02}'.format(r, g, b))

用递归的方法简单清晰地实现了十进制向任意进制转换。char定义了不同进制的各位数字如何表示;递归发生语句中radix()+ char[]的位置可以巧妙地完成余数的倒排。

R、G、B 三种颜色分别调用radix()可以用map()函数直接调用,省去重复的赋值、调用步骤,也能明显减少 Python 的用时。

Python 的 format()方法功能强大,{:>02}表示\{:\{\{fill\}align\}\{sign\}\{width\}\},也就是说>表示右对齐,0表示前导零,2表示宽度,如果输出的字符串或数字长度为2,那么不填充前导零0,如果长度不足2,那么根据右对齐从左填充。

另外,前导零的实现还有另一种表示方法,将0放在表示右对齐的>前面,表示用该字符填充。

print('#{:0>2}{:0>2}{:0>2}'.format(r, g, b))

参考来源

https://docs.python.org/zh-cn/3/library/string.html#formatspec