MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / is_luhn

Function is_luhn

hashes/luhn.py:6–35  ·  view source on GitHub ↗

Perform Luhn validation on an input string Algorithm: * Double every other digit starting from 2nd last digit. * Subtract 9 if number is greater than 9. * Sum the numbers * >>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713, ... 79927398714, 799

(string: str)

Source from the content-addressed store, hash-verified

4
5
6def is_luhn(string: str) -> bool:
7 """
8 Perform Luhn validation on an input string
9 Algorithm:
10 * Double every other digit starting from 2nd last digit.
11 * Subtract 9 if number is greater than 9.
12 * Sum the numbers
13 *
14 >>> test_cases = (79927398710, 79927398711, 79927398712, 79927398713,
15 ... 79927398714, 79927398715, 79927398716, 79927398717, 79927398718,
16 ... 79927398719)
17 >>> [is_luhn(str(test_case)) for test_case in 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] = [int(digit) for digit in __vector]
24
25 vector.reverse()
26 for i, digit in enumerate(vector):
27 if i & 1 == 0:
28 doubled: int = digit * 2
29 if doubled > 9:
30 doubled -= 9
31 check_digit += doubled
32 else:
33 check_digit += digit
34
35 return check_digit % 10 == 0
36
37
38if __name__ == "__main__":

Callers 1

luhn.pyFile · 0.85

Calls 1

reverseMethod · 0.80

Tested by

no test coverage detected