Repository navigation
Expand file tree
/
Copy pathluhn.py
More file actions
101 lines (67 loc) · 2.54 KB
/
Copy pathluhn.py
File metadata and controls
101 lines (67 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""Validate numbers and calculate or append check digits using the Luhn algorithm."""
from __future__ import annotations
from typing import Union
NumberLike = Union[str, int]
REMOVE_CHARS = " -./\\,"
DIGIT_CLEANUP_TABLE = str.maketrans("", "", REMOVE_CHARS)
def _digits(value: NumberLike) -> str:
"""Return only digits, allowing spaces, hyphens, dots, slashes, backslashes, and commas as separators."""
if isinstance(value, bool) or not isinstance(value, (str, int)):
raise TypeError("value must be a string or non-boolean integer")
cleaned = str(value).strip().translate(DIGIT_CLEANUP_TABLE)
if not cleaned or not cleaned.isdigit():
raise ValueError(
"value must contain digits only, with optional spaces, hyphens, "
"dots, slashes, backslashes, or commas"
)
return cleaned
def checksum(value: NumberLike) -> int:
"""Return the Luhn validation checksum for a complete number."""
digits = _digits(value)
total = 0
should_double = False
for digit in reversed(digits):
number = int(digit)
if should_double:
number *= 2
if number > 9:
number -= 9
total += number
should_double = not should_double
return total % 10
def is_valid(value: NumberLike) -> bool:
"""Return whether the value satisfies the Luhn algorithm."""
try:
is_valid_checksum = checksum(value) == 0
except (TypeError, ValueError):
return False
return is_valid_checksum
def calculate_check_digit(payload: NumberLike) -> int:
"""Return the Luhn check digit to append to the payload."""
digits = _digits(payload)
total = 0
should_double = True
for digit in reversed(digits):
number = int(digit)
if should_double:
number *= 2
if number > 9:
number -= 9
total += number
should_double = not should_double
return (10 - total % 10) % 10
def append_check_digit(payload: NumberLike) -> str:
"""Return the payload with a valid Luhn check digit appended."""
payload = _digits(payload)
return f"{payload}{calculate_check_digit(payload)}"
if __name__ == "__main__":
import argparse
import sys
parser = argparse.ArgumentParser(
description="Validate a number with the Luhn algorithm."
)
parser.add_argument("number", help="number to validate")
args = parser.parse_args()
valid = is_valid(args.number)
print("valid" if valid else "invalid")
sys.exit(0 if valid else 1)