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
Your code is nice -- well done for writing idiomatic Python! Here are some minor things:
When you see the idiom
result =
for elt in :
result += elt
you can replace it by a list comprehension. In this case:
result = sum((i+1)*int(digit) for i, digit in enumerate(digits)
or even more concisely:
return sum((i+1)*int(digit) for i, digit in enumerate(digits) % 11 == check_digit
Of course, it is a value judgement whether this is better than the original. I would personally consider the second of these to be best.
Also, the extra parentheses in (result % 11) == check_digit
are extraneous and I don't really think you need them for clarity. That leaves you overall with:
def validate(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if match:
digits = match.group(1) + match.group(2) + match.group(3)
parity = sum((i+1)*int(digit) for i, digit in enumerate(digits)
return parity % 11 == check_digit
else:
return False
Note that you do still need the return False
to catch the case that the ISBN is not even in the right format.