|
16 | 16 | If the result is 0, then it is a valid ISBN-10, otherwise it is invalid. |
17 | 17 | """ |
18 | 18 |
|
19 | | -ISBN: str = "0123456789X" |
20 | | - |
21 | | - |
22 | | -def formatted_isbn(isbn: str) -> list[int]: |
23 | | - """ |
24 | | - Extract and format ISBN digits from input string. |
25 | | -
|
26 | | - Converts ISBN string to list of integers, treating 'X' as 10. |
27 | | - Ignores non-digit characters except for trailing 'X'. |
28 | | -
|
29 | | - :param isbn: ISBN string that may contain digits, hyphens, and trailing 'X' |
30 | | - :return: List of integers representing ISBN digits, 'X' converted to 10 |
31 | | - """ |
32 | | - result: list[int] = [] |
33 | | - for char in isbn: |
34 | | - if char.isdigit(): |
35 | | - result.append(int(char)) |
36 | | - if isbn[-1] == "X": |
37 | | - result.append(10) |
38 | | - return result |
39 | | - |
40 | 19 |
|
41 | 20 | def is_valid(isbn: str) -> bool: |
42 | 21 | """ |
43 | 22 | Verify ISBN. |
44 | 23 |
|
45 | 24 | :param isbn: 9 digits ISBN 10 format |
46 | | - :return: Tru if isbn is valid, False otherwise |
| 25 | + :return: True if isbn is valid, False otherwise |
47 | 26 | """ |
48 | | - # Make sure that 'X' has an upper case |
49 | | - isbn = isbn.upper() |
50 | | - # Non ISBN chars or empty strings not allowed |
51 | | - if not all(char in ISBN for char in isbn.replace("-", "")) or not isbn: |
52 | | - return False |
53 | | - # In case X is present, it should be at the end of the string only |
54 | | - if "X" in isbn and isbn.index("X") != len(isbn) - 1: |
55 | | - return False |
56 | | - |
57 | | - # Convert all isbn chars to digits |
58 | | - isbn_digits: list[int] = formatted_isbn(isbn) |
| 27 | + isbn_digits: list[int] = [] |
| 28 | + for char in isbn: |
| 29 | + if char == "-": |
| 30 | + continue |
| 31 | + if char.isdigit(): |
| 32 | + isbn_digits.append(int(char)) |
| 33 | + elif char.upper() == "X" and len(isbn_digits) == 9: |
| 34 | + isbn_digits.append(10) |
| 35 | + else: |
| 36 | + return False |
59 | 37 | # ISBN total length should be = 10 |
60 | 38 | if len(isbn_digits) != 10: |
61 | 39 | return False |
|
0 commit comments