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

该博客介绍了如何将地球上的RGB颜色转换为火星上使用13进制表示的颜色编码。通过一个具体的20分编程题为例,讲解了进制转换和在Python中添加前导零的方法,包括使用`format`方法和字符串格式化。并提供了AC源代码,展示了如何用递归方式实现转换,并强调了代码复用和效率优化。
摘要由CSDN通过智能技术生成

题目内容

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值