1919ISBN : 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-
3522def 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