Python刷题笔记(5) - 判断“幸运数”
来源:互联网 发布:驱动保护编程 编辑:程序博客网 时间:2024/04/30 11:15
题目:
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers:
003111 # 3 = 1 + 1 + 1813372 # 8 + 1 + 3 = 3 + 7 + 217935 # 1 + 7 = 3 + 556328116 # 5 + 6 + 3 + 2 = 8 + 1 + 1 + 6
Such tickets were either eaten after being used or collected for bragging rights.
Your task is to write a funtion luck_check(str)
, which returns true/True
if argument is string decimal representation of a lucky ticket number, orfalse/False
for all other numbers. It should throw errors for empty strings or strings which don't represent a decimal number.
中文简介:
判断输入的字符串是否幸运数,所谓幸运数就是将数字从中间分段,左边各位数相加等于右边各位数相加
想法:
1、对字符串输入进行判断,不为数字则扔出一个异常
2、将输入字符串对半切片,然后历遍两边边的各个字符,变为整数后再求和
3、切片的时候应注意字符串的长度为奇数还是偶数
实现:
import redef luck_check(string): if re.match('[^0-9]',string): raise Exception('error input') if len(string) == 1: raise Exception('error input') else: if len(string) % 2 == 0: p = sum(int(s) for s in string[:len(string)/2]) q = sum(int(s) for s in string[len(string)/2:]) if p == q: return True else: p = sum(int(s) for s in string[:len(string)/2]) q = sum(int(s) for s in string[len(string)/2 + 1:]) if p == q: return True return False
对比总结:
提交完成后,对比首位的解决方法,发现处理字符长度为奇偶的方式非常巧妙。直接建立两个自变量,分别等于len(string)和len(string)+1,然后前面的切片切到len(string)/2,后面的切到(len(string)+1)/2,这样就可以不用分别处理奇偶长度了。另外,作者使用整除‘//’而不是我用的'/',虽然在python2.7下没问题,但是3.0的时候整数相除返回的也是浮点数了,这样处理应该会兼容。此外,使用了map()函数来直接进行数字处理,比我用的循环+int()函数的笨拙方式要更高明
- Python刷题笔记(5) - 判断“幸运数”
- Python刷题笔记(1)- 数独判断
- JTextField判断幸运数
- Algorithm学习笔记 --- 幸运数(堆)
- 幸运数(模拟)
- 幸运数,c语言幸运数,算法比赛题
- 蓝桥杯-幸运数(模拟)
- 蓝桥杯 幸运数(暴力?)
- 下一个幸运数(AOJ840)
- Python学习笔记0002:判断正负数
- 【Python 学习笔记】判断回文数/字符
- 幸运数
- 幸运数
- 幸运数
- 幸运数
- 幸运数
- 幸运数
- 幸运数
- JavaScript 的性能优化:加载和执行
- 类练习题2:堆栈和队列类
- 定时器的简单示例(setInterval clearInterval)
- MySQL记录存在则更新,不存在插入on duplicate key update
- 使用WebViewJavascriptBridge实现OC与JS交互
- Python刷题笔记(5) - 判断“幸运数”
- R语言基本画图
- make:commands commence before first target
- Android DPI
- session, sessionID和cookie
- PHP的三种XML解析器之SimpleXML解析器(三)
- 2015.11.10 ,Demo7 ,构造函数 ,重载 ,子类的重写,this关键字的使用,继承
- HttpClient4.3教程 第四章 HTTP认证
- 第一章百宝云基础语法新手教程第三节流程语句