In: Computer Science
(Business: check ISBN-13)
ISBN-13 is a new standard for indentifying books. It uses 13 digits d1d2d3d4d5d6d7d8d910d11d12d13 . The last digit d13 is a checksum, which is calculated from the other digits using the following formula:
10 - (d1 + 3*d2 + d3 + 3*d4 + d5 + 3*d6 + d7 + 3*d8 + d9 + 3*d10 + d11 + 3*d12) % 10
If the checksum is 10, replace it with 0. Your program should read the input as a string. Display “incorrect input” if the input is incorrect.
Sample Run 1
Enter the first 12 digits of an ISBN-13 as a string: 978013213080
The ISBN-13 number is 9780132130806
Sample Run 2
Enter the first 12 digits of an ISBN-13 as a string: 978013213079
The ISBN-13 number is 9780132130790.
In Python.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
#code
#method to validate the input
#returns true if isbn is a 12 digit number
def isValidInput(isbn):
#if length is not 12, returns False
if len(isbn)!=12:
return
False
#defining a string of digits
digits='0123456789'
#loops through each character in
isbn
for i in
isbn:
#if i is not a
digit, returns False
if
not i in digits:
return False
return True #all checks
passed
#method to find the checksum, given the validated isbn
def findChecksum(isbn):
#converting isbn into a list of digits
digits=[int(i) for i
in isbn]
#variable to store the sum of digits
temp=0
#looping through digits
for i in
range(len(digits)):
#if i is an even
index,simply adding digit at index i to temp
if
i%2==0:
temp+=digits[i]
#otherwise,
multiplying current element by 3 and adding
else:
temp+=3*digits[i]
#finding result of temp modulo 10
mod=temp%10
#finding checksum by subtracting from
10
checksum=10-mod
#returning 0 if checksum is 10.
if checksum==10:
return
0
else:
#returning checksum
as it is
return checksum
if __name__ == '__main__':
#getting input, validating, printing
results
isbn=input('Enter the first 12
digits of an ISBN-13 as a string: ')
if isValidInput(isbn):
checksum=findChecksum(isbn)
isbn_13=isbn+str(checksum)
print('The
ISBN-13 number is',isbn_13)
else:
print('incorrect
input')
#output (two runs)
Enter the first 12 digits of an ISBN-13 as a string: 978013213080 The ISBN-13 number is 9780132130806 Enter the first 12 digits of an ISBN-13 as a string: 978013213079 The ISBN-13 number is 9780132130790