Skip to content

Commit da97d5a

Browse files
committed
Update isbn_verifier.py
1 parent 9045523 commit da97d5a

File tree

1 file changed

+9
-14
lines changed

1 file changed

+9
-14
lines changed

isbn-verifier/isbn_verifier.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,19 +19,6 @@
1919
ISBN: str = "0123456789X"
2020

2121

22-
def calc_formula(digits: list[int]) -> int:
23-
"""
24-
Calculate the weighted sum for ISBN-10 validation formula.
25-
26-
:param digits: List of integer digits to calculate the formula for
27-
:return: The weighted sum result used in ISBN-10 validation
28-
"""
29-
result: int = 0
30-
for i, digit in enumerate(digits):
31-
result += digit * (10 - i)
32-
return result
33-
34-
3522
def formatted_isbn(isbn: str) -> list[int]:
3623
"""
3724
Extract and format ISBN digits from input string.
@@ -48,6 +35,8 @@ def formatted_isbn(isbn: str) -> list[int]:
4835
result.append(int(char))
4936
if isbn[-1].lower() == "x":
5037
result.append(10)
38+
39+
print(f"result: {result}, len: {len(result)}")
5140
return result
5241

5342

@@ -61,10 +50,16 @@ def is_valid(isbn: str) -> bool:
6150
# Non ISBN chars or empty strings not allowed
6251
if not all(char in ISBN for char in isbn.replace("-", "")) or not isbn:
6352
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+
6457
# Convert all isbn chars to digits
6558
isbn_digits: list[int] = formatted_isbn(isbn)
6659
# ISBN total length should be = 10
6760
if len(isbn_digits) != 10:
6861
return False
6962

70-
return calc_formula(isbn_digits) % 11 == 0
63+
return (
64+
sum(digit * (10 - i) for i, digit in enumerate(isbn_digits)) % 11 == 0
65+
)

0 commit comments

Comments
 (0)