Python: luhn
This commit is contained in:
parent
64012ef885
commit
c3f7675134
4 changed files with 218 additions and 0 deletions
30
python/luhn/luhn.py
Normal file
30
python/luhn/luhn.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import re
|
||||
|
||||
class Luhn:
|
||||
def __init__(self, card_num):
|
||||
|
||||
pattern = re.compile(r'\s+')
|
||||
card_num = re.sub(pattern, '', card_num)
|
||||
|
||||
if not card_num.isnumeric() or len(card_num) < 2:
|
||||
self.is_valid = False
|
||||
else:
|
||||
|
||||
checksum = 0
|
||||
|
||||
for i, ch in enumerate(reversed(card_num)):
|
||||
|
||||
x = int(ch)
|
||||
|
||||
if i % 2:
|
||||
x *= 2
|
||||
|
||||
if x > 9:
|
||||
x -= 9
|
||||
|
||||
checksum += x
|
||||
|
||||
self.is_valid = not (checksum % 10)
|
||||
|
||||
def valid(self):
|
||||
return self.is_valid
|
||||
Loading…
Add table
Add a link
Reference in a new issue