|
| 1 | +""" |
| 2 | +ISBN Verifier. |
| 3 | +
|
| 4 | +The ISBN-10 verification process is used to validate book identification |
| 5 | +numbers. These normally contain dashes and look like: 3-598-21508-8 |
| 6 | +
|
| 7 | +ISBN |
| 8 | +The ISBN-10 format is 9 digits (0 to 9) plus one check character |
| 9 | +(either a digit or an X only). In the case the check character is an X, |
| 10 | +this represents the value '10'. These may be communicated with or without |
| 11 | +hyphens, and can be checked for their validity by the following formula: |
| 12 | +
|
| 13 | +(d₁ * 10 + d₂ * 9 + d₃ * 8 + d₄ * 7 + d₅ * 6 + |
| 14 | +d₆ * 5 + d₇ * 4 + d₈ * 3 + d₉ * 2 + d₁₀ * 1) mod 11 == 0 |
| 15 | +
|
| 16 | +If the result is 0, then it is a valid ISBN-10, otherwise it is invalid. |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +def calc_formula(digits: str) -> int: |
| 21 | + """ |
| 22 | + Calculate the weighted sum for ISBN-10 validation formula. |
| 23 | +
|
| 24 | + :param digits: List of integer digits to calculate the formula for |
| 25 | + :return: The weighted sum result used in ISBN-10 validation |
| 26 | + """ |
| 27 | + result: int = 0 |
| 28 | + for i, digit in enumerate(digits): |
| 29 | + if digit.isdigit(): |
| 30 | + result += int(digit) * (10 - i) |
| 31 | + elif digit.lower() == "x": |
| 32 | + result += 10 * 1 |
| 33 | + else: |
| 34 | + # Invalid char, calc failed |
| 35 | + return 1 |
| 36 | + return result |
| 37 | + |
| 38 | + |
| 39 | +def is_valid(isbn: str) -> bool: |
| 40 | + """ |
| 41 | + Verify ISBN. |
| 42 | +
|
| 43 | + :param isbn: 9 digits ISBN 10 format |
| 44 | + :return: Tru if isbn is valid, False otherwise |
| 45 | + """ |
| 46 | + formated_isbn: str = isbn.replace("-", "") |
| 47 | + if len(formated_isbn) != 10: |
| 48 | + return False |
| 49 | + |
| 50 | + return calc_formula(formated_isbn) % 11 == 0 |
0 commit comments