Checking if an ISBN number is correct

前端 未结 8 1615
臣服心动
臣服心动 2020-12-28 20:43

I\'m given some ISBN numbers e.g. 3-528-03851 (not valid) , 3-528-16419-0 (valid). I\'m supposed to write a program which tests if the ISBN number

相关标签:
8条回答
  • 2020-12-28 21:16

    check this after you have finished ok :)

    http://www.staff.ncl.ac.uk/d.j.wilkinson/software/isbn.py

    and

    http://chrisrbennett.com/2006/11/isbn-check-methods.html

    EDIT : Sorry about the confusing i didn't see the homework tag but maybe after finishing your homework you can see what other have done before, i think you can learn a lot from others code ; sorry again :(

    0 讨论(0)
  • 2020-12-28 21:19
    • The check_digit initialization can raise a ValueError if the last character isn't a decimal digit. Why not pull out the check digit with your regex instead of using slicing?
    • Instead of search, you should probably use match, unless you want to allow arbitrary junk as the prefix. (Also, as a rule of thumb I'd anchor the end with $, though in your case that won't matter as your regex is fixed-width.)
    • Instead of manually listing the groups, you could just use ''.join(match.groups()), and pull the check_digit out afterwards. You might as well do the conversion to ints before pulling it out, as you want to convert all of them to ints anyway.
    • your for loop could be replaced by a list/generator comprehension. Just use sum() to add up the elements.
    • True if (expression) else False can generally be replaced with simply expression. Likewise, False if (expression) else True can always be replaced with simply not expression

    Putting that all together:

    def check(isbn):
        match = re.match(r'(\d)-(\d{3})-(\d{5})-(\d)$', isbn)
        if match:
            digits = [int(x) for x in ''.join(match.groups())]
            check_digit = digits.pop()
            return check_digit == sum([(i + 1) * digit
                                      for i, digit in enumerate(digits)]) % 11
        return False
    

    The last line is arguably unnecessary, as the default behavior would be to return None (which is falsy), but explicit returns from some paths and not from others looks like a bug to me, so I think it's more readable to leave it in.

    0 讨论(0)
提交回复
热议问题