forked from JaredLGillespie/CodinGame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
isbn-check-digit.py
47 lines (35 loc) · 1023 Bytes
/
isbn-check-digit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def is_valid_isbn(isbn):
if len(isbn) not in (10, 13): return False
if 'X' in isbn[:-1]: return False
if len(isbn) == 10: return is_valid_isbn10(isbn)
return is_valid_isbn13(isbn)
def is_valid_isbn10(isbn):
w = 10
s = 0
for d in isbn[:-1]:
s += w * int(d)
w -= 1
if s % 11 == 0: return isbn[-1] == '0'
if s % 11 == 1: return isbn[-1] == 'X'
if isbn[-1] == 'X': return False
return int(isbn[-1]) == 11 - s % 11
def is_valid_isbn13(isbn):
w = 1
s = 0
for d in isbn[:-1]:
s += w * int(d)
w ^= 2
if s % 10 == 0: return isbn[-1] == '0'
if isbn[-1] == 'X': return False
return int(isbn[-1]) == 10 - s % 10
def solution():
num_isbns = int(input())
invalid_isbns = []
for _ in range(num_isbns):
isbn = input()
if not is_valid_isbn(isbn):
invalid_isbns.append(isbn)
print('{} invalid:'.format(len(invalid_isbns)))
for isbn in invalid_isbns:
print(isbn)
solution()