Editor

Valid ISBN

#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:

  • ISBN-10: ten characters, where the first nine are digits and the last is a digit or a capital 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.
  • ISBN-13: thirteen digits. Multiply them by 1, 3, 1, 3 and so on, alternating (the first by 1, the second by 3, the last by 1), and add the products: the code is valid when the sum is a multiple of 10.

Anything else is not valid: any other length, an X anywhere except the last place of an ISBN-10, or any other character.

Examples

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.

Constraints

  • code has 0 to 50 characters.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.