fork(1) download
  1. """
  2.  
  3. NOTE: Haskell code
  4.  
  5. import Char(digitToInt)
  6.  
  7. calcCheckDigit :: [Int] -> Int
  8. calcCheckDigit = (`mod` 10) . (10 -) . sum . zipWith (*) (cycle [1,3])
  9.  
  10. isValidISBN13 :: [Char] -> Bool
  11. isValidISBN13 isbn =
  12. if (length isbn) /= 13 then
  13. False
  14. else
  15. let digits = (map digitToInt isbn) in
  16. (==) (last digits) (calcCheckDigit (take 12 digits))
  17.  
  18. """
  19.  
  20. def is_valid_isbn13(isbn):
  21. from string import digits
  22. from operator import mul
  23. from itertools import cycle, starmap, izip
  24.  
  25. assert isinstance(isbn, str)
  26. assert len(isbn) == 13
  27. assert all(c for c in isbn if c in digits) # all(map(digits.__contains__, isbm))
  28.  
  29. return int(isbn[-1]) == (10-sum(starmap(mul,izip(map(int,isbn[:-1]),cycle([1,3])))))%10
  30.  
  31. if __name__ == '__main__':
  32. print is_valid_isbn13("9784062772211")
  33. print is_valid_isbn13("9784150315684")
  34.  
Success #stdin #stdout 0.02s 4860KB
stdin
Standard input is empty
stdout
True
False