30 lines
610 B
Python
30 lines
610 B
Python
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
|