2024-03-13 06:52:41 +00:00
|
|
|
"""Luhn Algorithm"""
|
|
|
|
|
2021-09-07 11:37:03 +00:00
|
|
|
from __future__ import annotations
|
2021-06-13 18:19:44 +00:00
|
|
|
|
|
|
|
|
|
|
|
def is_luhn(string: str) -> bool:
|
|
|
|
"""
|
2021-08-27 09:45:14 +00:00
|
|
|
Perform Luhn validation on an input string
|
2021-06-13 18:19:44 +00:00
|
|
|
Algorithm:
|
|
|
|
* Double every other digit starting from 2nd last digit.
|
|
|
|
* Subtract 9 if number is greater than 9.
|
|
|
|
* Sum the numbers
|
|
|
|
*
|
2021-08-27 09:45:14 +00:00
|
|
|
>>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
|
2021-06-13 18:19:44 +00:00
|
|
|
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
|
2021-08-27 09:45:14 +00:00
|
|
|
... 79927398719)
|
|
|
|
>>> [is_luhn(str(test_case)) for test_case in test_cases]
|
2021-06-13 18:19:44 +00:00
|
|
|
[False, False, False, True, False, False, False, False, False, False]
|
|
|
|
"""
|
|
|
|
check_digit: int
|
2021-09-07 11:37:03 +00:00
|
|
|
_vector: list[str] = list(string)
|
2021-06-13 18:19:44 +00:00
|
|
|
__vector, check_digit = _vector[:-1], int(_vector[-1])
|
2021-09-07 11:37:03 +00:00
|
|
|
vector: list[int] = [int(digit) for digit in __vector]
|
2021-06-13 18:19:44 +00:00
|
|
|
|
|
|
|
vector.reverse()
|
2021-08-27 09:45:14 +00:00
|
|
|
for i, digit in enumerate(vector):
|
|
|
|
if i & 1 == 0:
|
|
|
|
doubled: int = digit * 2
|
2021-06-13 18:19:44 +00:00
|
|
|
if doubled > 9:
|
|
|
|
doubled -= 9
|
|
|
|
check_digit += doubled
|
|
|
|
else:
|
2021-08-27 09:45:14 +00:00
|
|
|
check_digit += digit
|
2021-06-13 18:19:44 +00:00
|
|
|
|
2021-08-27 09:45:14 +00:00
|
|
|
return check_digit % 10 == 0
|
2021-06-13 18:19:44 +00:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|
|
|
|
assert is_luhn("79927398713")
|
2021-08-27 09:45:14 +00:00
|
|
|
assert not is_luhn("79927398714")
|