# Python刷题笔记（5） - 判断“幸运数”

392人阅读 评论(0)

#### 题目：

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 + 1
813372    #     8 + 1 + 3 = 3 + 7 + 2
17935     #         1 + 7 = 3 + 5
56328116  # 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, or false/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 re
def 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

#### 对比总结：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：8111次
• 积分：179
• 等级：
• 排名：千里之外
• 原创：10篇
• 转载：0篇
• 译文：0篇
• 评论：1条
文章分类
文章存档
阅读排行
评论排行
最新评论