#294 · Codes and ciphers · Intermediate · 65 XP · about 12 min
Every book has an ISBN, an identifier whose last character is a check digit that catches most typing mistakes. Older books use ISBN-10 and newer ones ISBN-13. Write isbn_valid(code) that returns True if code is a valid ISBN-10 or a valid ISBN-13, and False otherwise.
First remove every hyphen (-) and every space from code. What is left must then be one of these two:
X, which stands for 10. Multiply the ten values by 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 in order and add the products: the code is valid when the sum is a multiple of 11.Anything else is not valid: any other length, an X anywhere except the last place of an ISBN-10, or any other character.
isbn_valid("1-60309-447-4") # returns True isbn_valid("0-8044-2957-X") # returns True isbn_valid("978-1-60309-447-4") # returns True isbn_valid("978-1-60309-447-5") # returns False
For the first example the sum is 1 * 10 + 6 * 9 + 0 * 8 + 3 * 7 + 0 * 6 + 9 * 5 + 4 * 4 + 4 * 3 + 7 * 2 + 4 * 1 = 176, which is 16 * 11.
code has 0 to 50 characters.First solves only, ranked by stars and then time.