Back to Freecodecamp

Challenge 231: ISBN-10 Validator

curriculum/challenges/english/blocks/daily-coding-challenges-python/69b1028d6e265413d0198a2a.md

latest2.0 KB
Original Source

--description--

Given a string, determine if it's a valid ISBN-10.

An ISBN-10 consists of hyphens ("-") and 10 other characters. After removing the hyphens ("-"):

  • The first 9 characters must be digits, and
  • The final character may be a digit or the letter "X", which represents the number 10.

To validate it:

  • Multiply each digit (or value) by its position (multiply the first digit by 1, the second by 2, and so on).
  • Add all the results together.
  • If the total is divisible by 11, it's valid.

--hints--

is_valid_isbn10("0-306-40615-2") should return True.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_isbn10("0-306-40615-2"), True)`)
}})

is_valid_isbn10("0-306-40615-1") should return False.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_isbn10("0-306-40615-1"), False)`)
}})

is_valid_isbn10("0-8044-2957-X") should return True.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_isbn10("0-8044-2957-X"), True)`)
}})

is_valid_isbn10("X-306-40615-2") should return False.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_isbn10("X-306-40615-2"), False)`)
}})

is_valid_isbn10("0-6822-2589-4") should return True.

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertIs(is_valid_isbn10("0-6822-2589-4"), True)`)
}})

--seed--

--seed-contents--

py
def is_valid_isbn10(s):

    return s

--solutions--

py
def is_valid_isbn10(s):
    isbn = s.replace("-", "")

    if len(isbn) != 10:
        return False

    total = 0

    for i in range(9):
        if not isbn[i].isdigit():
            return False
        total += int(isbn[i]) * (i + 1)

    last = isbn[9]

    if last == "X":
        total += 10 * 10
    elif last.isdigit():
        total += int(last) * 10
    else:
        return False

    return total % 11 == 0