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
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 :(
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?$
, though in your case that won't matter as your regex is fixed-width.)''.join(match.groups())
, and pull the check_digit
out afterwards. You might as well do the conversion to int
s before pulling it out, as you want to convert all of them to int
s anyway.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.