Problem 2 – isbn.py: ISBN validation [15 points] The International Standard Book
ID: 3713154 • Letter: P
Question
Problem 2 – isbn.py: ISBN validation [15 points] The International Standard Book Number (ISBN) is a 10-digit code that uniquely specifies a book. The rightmost digit is a checksum digit chosen so that the quantity d1 + 2d2 + 3d3 + · · · + 10d10 is a multiple of 11. Here di denotes the i-th digit from the right, i.e., the full ISBN number is d10d9d8d7d6d5d4d3d2d1. The checksum digit d1 can be any value from 0 to 10. The ISBN convention is to use the character X to denote 10. Example: the checksum digit corresponding to 020131452 is 5, since 5 is the only value of d1 between 0 and 10 such that 10 · 0 + 9 · 2 + 8 · 0 + 7 · 1 + 6 · 3 + 5 · 1 + 4 · 4 + 3 · 5 + 2 · 2 + 1 · d1 is a multiple of 11. Write a function is_isbn_valid() that takes a string isbn as an argument, computes the checksum, and returns True if it represents a valid ISBN number, and False otherwise. You can assume the input is correct, i.e., it has length 10 and consists of only decimal digits (except, possibly, the first character which could also be ’X’). Hint: You will need to use indexing and/or slicing over the string isbn, as well as the built-in function int() to convert numbers (which includes individual digits) from string to integer. Probably the simplest approach is to iterate over individual characters of the input string, initializing your checksum value based on isbn[-1] and then writing an accumulation loop that iterates over the remaining digits to compute the full checksum value. Finally you need to check if the checksum is a multiple of 11 or not. Another possibility is to convert isbn[:-1] to an integer and write your accumulation loop in terms of that instead (see also the hint in previous problem about iterating over the digits of an integer. Practice goal: Further practice with accumulation loops. Very similar checksumming methods are frequently used, e.g., for UPCs, credit cards (Luhn’s algorithm), etc.
Explanation / Answer
def is_isbn_valid(isbn):
if (isbn==None) or (len(isbn) != 10):
return False
checksum = 0
end = 10
if isbn[9] == 'X':
end = 9
checksum = 10
for i in range(0, end):
checksum += (10-i)*int(isbn[i])
return checksum % 11 == 0
print(is_isbn_valid('0201314525'))
# copy pastable code link: https://paste.ee/p/SbCfm
Sample run
True
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.