关闭

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

对比总结:

提交完成后,对比首位的解决方法,发现处理字符长度为奇偶的方式非常巧妙。直接建立两个自变量,分别等于len(string)和len(string)+1,然后前面的切片切到len(string)/2,后面的切到(len(string)+1)/2,这样就可以不用分别处理奇偶长度了。另外,作者使用整除‘//’而不是我用的'/',虽然在python2.7下没问题,但是3.0的时候整数相除返回的也是浮点数了,这样处理应该会兼容。此外,使用了map()函数来直接进行数字处理,比我用的循环+int()函数的笨拙方式要更高明

0
0

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