checksums.py 629 B

1234567891011121314151617181920212223
  1. from typing import List
  2. def luhn_checksum(number: float) -> int:
  3. def digits_of(n: float) -> List[int]:
  4. return [int(d) for d in str(n)]
  5. digits = digits_of(number)
  6. odd_digits = digits[-1::-2]
  7. even_digits = digits[-2::-2]
  8. checksum = 0
  9. checksum += sum(odd_digits)
  10. for d in even_digits:
  11. checksum += sum(digits_of(d * 2))
  12. return checksum % 10
  13. def calculate_luhn(partial_number: float) -> int:
  14. """
  15. Generates the Checksum using Luhn's algorithm
  16. """
  17. check_digit = luhn_checksum(int(partial_number) * 10)
  18. return check_digit if check_digit == 0 else 10 - check_digit