Skip to content

Commit 95a4957

Browse files
Luhn algorithm (#4487)
* Luhn algorithm Perform Luhn validation on input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers https://en.wikipedia.org/wiki/Luhn_algorithm * Update DIRECTORY.md * Update luhn.py * Update luhn.py * Update luhn.py * Update luhn.py * Update DIRECTORY.md
1 parent 10d38ea commit 95a4957

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

hashes/luhn.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
""" Luhn Algorithm """
2+
from typing import List
3+
4+
5+
def is_luhn(string: str) -> bool:
6+
"""
7+
Perform Luhn validation on input string
8+
Algorithm:
9+
* Double every other digit starting from 2nd last digit.
10+
* Subtract 9 if number is greater than 9.
11+
* Sum the numbers
12+
*
13+
>>> test_cases = [79927398710, 79927398711, 79927398712, 79927398713,
14+
... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
15+
... 79927398719]
16+
>>> test_cases = list(map(str, test_cases))
17+
>>> list(map(is_luhn, test_cases))
18+
[False, False, False, True, False, False, False, False, False, False]
19+
"""
20+
check_digit: int
21+
_vector: List[str] = list(string)
22+
__vector, check_digit = _vector[:-1], int(_vector[-1])
23+
vector: List[int] = [*map(int, __vector)]
24+
25+
vector.reverse()
26+
for idx, i in enumerate(vector):
27+
28+
if idx & 1 == 0:
29+
doubled: int = vector[idx] * 2
30+
if doubled > 9:
31+
doubled -= 9
32+
33+
check_digit += doubled
34+
else:
35+
check_digit += i
36+
37+
if (check_digit) % 10 == 0:
38+
return True
39+
return False
40+
41+
42+
if __name__ == "__main__":
43+
import doctest
44+
45+
doctest.testmod()
46+
assert is_luhn("79927398713")

0 commit comments

Comments
 (0)