forked from course-work/week1
98 lines
2.4 KiB
Python
98 lines
2.4 KiB
Python
class CreditCard:
|
|
card_types = [
|
|
# (starts with digits, card type, card length)
|
|
('4', 'VISA', 16),
|
|
('34', 'AMEX', 15),
|
|
('37', 'AMEX', 15),
|
|
('51', 'MASTERCARD', 16),
|
|
('52', 'MASTERCARD', 16),
|
|
('53', 'MASTERCARD', 16),
|
|
('54', 'MASTERCARD', 16),
|
|
('55', 'MASTERCARD', 16),
|
|
('6011', 'DISCOVER', 16),
|
|
]
|
|
|
|
@classmethod
|
|
def luna_check(cls, card_number):
|
|
digits = []
|
|
for index, digit in enumerate(card_number[::-1]):
|
|
if index % 2:
|
|
digits += [int(i) for i in str(int(digit)*2)]
|
|
else:
|
|
digits.append(int(digit))
|
|
|
|
return not bool(sum(digits) % 10)
|
|
|
|
def __init__(self, card_number):
|
|
self.card_number = card_number
|
|
self.is_valid, self.card_type = self.__is_valid() or (False, 'INVALID')
|
|
|
|
def __card_type(self):
|
|
for start, type, length in self.card_types:
|
|
if self.card_number.startswith(start):
|
|
|
|
return type, length
|
|
|
|
def __is_valid(self):
|
|
card_type = self.__card_type()
|
|
if card_type:
|
|
length = len(self.card_number) == card_type[1]
|
|
luna = self.luna_check(self.card_number)
|
|
if length and luna:
|
|
|
|
return True, card_type[0]
|
|
|
|
|
|
#Create and add your method called 'validate' to the CreditCard class here:
|
|
|
|
|
|
|
|
|
|
|
|
# # print(CreditCard.luna_check('4485040993287616'))
|
|
# cc = CreditCard('4485040993287616')
|
|
|
|
# print(cc.is_valid)
|
|
# exit(0)
|
|
|
|
#do not modify assert statements
|
|
|
|
cc = CreditCard('9999999999999999')
|
|
|
|
assert(cc.is_valid == False)
|
|
assert(cc.card_type == "INVALID")
|
|
|
|
cc = CreditCard('4440')
|
|
|
|
assert cc.is_valid == False, "4440 is too short to be valid"
|
|
assert cc.card_type == "INVALID", "4440 card type is INVALID"
|
|
|
|
cc = CreditCard('5515460934365316')
|
|
|
|
assert cc.is_valid == True, "Mastercard is Valid"
|
|
assert cc.card_type == "MASTERCARD", "card_type is MASTERCARD"
|
|
|
|
cc = CreditCard('6011053711075799')
|
|
|
|
assert cc.is_valid == True, "Discover Card is Valid"
|
|
assert cc.card_type == "DISCOVER", "card_type is DISCOVER"
|
|
|
|
cc = CreditCard('379179199857686')
|
|
|
|
assert cc.is_valid == True, "AMEX is Valid"
|
|
assert cc.card_type == "AMEX", "card_type is AMEX"
|
|
|
|
cc = CreditCard('4929896355493470')
|
|
|
|
assert cc.is_valid == True, "Visa Card is Valid"
|
|
assert cc.card_type == "VISA", "card_type is VISA"
|
|
|
|
cc = CreditCard('4329876355493470')
|
|
|
|
assert cc.is_valid == False, "This card does not meet mod10"
|
|
assert cc.card_type == "INVALID", "card_type is INVALID"
|
|
|
|
cc = CreditCard('339179199857685')
|
|
|
|
assert cc.is_valid == False, "Validates mod10, but invalid starting numbers for AMEX"
|
|
assert cc.card_type == "INVALID", "card_type is INVALID" |