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