Skip to content

Commit 4cfbb9b

Browse files
authored
Merge pull request #124 from ikostan/main
Update isbn_verifier.py
2 parents a392d0b + b54a371 commit 4cfbb9b

File tree

1 file changed

+11
-33
lines changed

1 file changed

+11
-33
lines changed

isbn-verifier/isbn_verifier.py

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -16,46 +16,24 @@
1616
If the result is 0, then it is a valid ISBN-10, otherwise it is invalid.
1717
"""
1818

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-
4019

4120
def is_valid(isbn: str) -> bool:
4221
"""
4322
Verify ISBN.
4423
4524
: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
4726
"""
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
5937
# ISBN total length should be = 10
6038
if len(isbn_digits) != 10:
6139
return False

0 commit comments

Comments
 (0)