10 Row Abacus
输入一个数字,按规定输出符号排列。此题的原型为算盘,用符号排列模拟算盘的显示。具体要求如下
######################################################################### # 10-row School abacus # by # Michael H ######################################################################### # Description partially extracted from from wikipedia # # Around the world, abaci have been used in pre-schools and elementary # # In Western countries, a bead frame similar to the Russian abacus but # with straight wires and a vertical frame has been common (see image). # Helps schools as an aid in teaching the numeral system and arithmetic # # |00000***** | row factor 1000000000 # |00000***** | row factor 100000000 # |00000***** | row factor 10000000 # |00000***** | row factor 1000000 # |00000***** | row factor 100000 # |00000***** | row factor 10000 # |00000***** | row factor 1000 # |00000**** *| row factor 100 * 1 # |00000*** **| row factor 10 * 2 # |00000** ***| row factor 1 * 3 # ----------- # Sum 123 # # Each row represents a different row factor, starting with x1 at the # bottom, ascending up to x1000000000 at the top row. ###################################################################### # TASK: # Define a procedure print_abacus(integer) that takes a positive integer # and prints a visual representation (image) of an abacus setup for a # given positive integer value. # # Ranking # 1 STAR: solved the problem! # 2 STARS: 6 < lines <= 9 # 3 STARS: 3 < lines <= 6 # 4 STARS: 0 < lines <= 3
最终的判定是以实现效果所写代码的行数,可见这里是要我们在练习基本语法的同时,去思考最紧凑的方法。
对于算盘来说,在初始状态每一列都是相同的,且输入数字的权重和列数是对应的,从对实际问题的映射和评分要求考虑,下面的代码十分吻合
def print_abacus(value): for c in ((10 - len(str(value))) * '0' + str(value)): print('|00000*****|'[ : -1 - int(c)] + ' ' + '|00000*****|'[-1 - int(c) : ])
但是一种更为容易想到,使用简单逻辑判断的方法如下
def print_abacus(value): num_len = len(str(value)) for i in range(10 - num_len): print('|00000***** |') for c in str(value): c_int = int(c) if(c_int > 5): print('|' + (10 - c_int) * '0' + ' ' + (c_int - 5) * '0' + '*****|') else: print('|00000' + (5 - c_int) * '*' + ' ' + c_int * '*' + '|')
题目及解答参考来自Udacity的Intro to Computer Science课程:https://classroom.udacity.com/courses/cs101/lessons/48689154/concepts/6986185940923
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?