One of my resolutions this year is to try to increase the number of opportunities I have to practice programming — something I really enjoy doing. Fortuitously, this article appeared in my inbox today, so I figured that I’d give it a whirl. All in all, it took me about 10 minutes to complete and helped me to reinforce some basic Python skills. It also will give me a change to experiment with a new code formatting plugin in WordPress. In the future I think that I’m going to post my practice sessions here.
This particular solution is focused on validating ISBN-10 codes and explores basic string slicing as well as the use of the modulus operator in Python. It was a nice diversion!
Here is my solution:
def isbn_exercise():
def validate_isbn10(code_string: str) -> bool:
# Check 10 digits and first 9 as numeric
if len(code_string) != 10 or not code_string[0:9].isnumeric():
return False
checksum = 0
for i in range(0, 10):
if i == 9 and code_string[i].lower() == "x":
digit = 10
else:
digit = int(code_string[i])
checksum += digit * (10 - i)
return (checksum % 11) == 0
isbn = "123"
assert validate_isbn10(isbn) is False
isbn = "0136091814"
assert validate_isbn10(isbn) is True
isbn = "1616550416"
assert validate_isbn10(isbn) is False
isbn = "0553418025"
assert validate_isbn10(isbn) is True
isbn = "3859574859"
assert validate_isbn10(isbn) is False
print("Exercise 10 - Complete!")
