Created
November 2, 2023 12:22
-
-
Save cookernetes/666fafa5fb5e01b8dbd6f5ee1b43fcc7 to your computer and use it in GitHub Desktop.
ISBN-13 Validator w/ Check Digit Validation (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
test_good_isbns = ["978-0-596-52068-7", "9780596520687"] | |
isbn_13_pattern = re.compile(r"^[0-9]{3}[\s-]?[0-9][\s-]?[0-9]{3}[\s-]?[0-9]{5}[\s-]?[0-9]$") | |
class ISBN13: | |
def __init__(self, isbn_in): | |
self.isbn = isbn_in | |
def validate(self): | |
return isbn_13_pattern.match(self.isbn) is not None and sum( | |
[*map(lambda char_w_i: int(char_w_i[1]) * 3 if char_w_i[0] % 2 == 0 else int(char_w_i[1]), | |
enumerate(re.sub(r"-|\s", "", self.isbn[:-1])))]) % 10 == int(self.isbn[-1]) | |
if __name__ == "__main__": | |
for code in test_good_isbns: | |
isbn = ISBN13(code) | |
print(isbn.validate()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment