1 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超6個(gè)贊
我認(rèn)為問(wèn)題在于您的代碼使用的是絕對(duì)奇偶校驗(yàn)而不是相對(duì)奇偶校驗(yàn)。也就是說(shuō),我們從右邊的倒數(shù)第二個(gè)數(shù)字開始加倍,然后每隔一個(gè)數(shù)字向左移動(dòng)。但是要加倍的數(shù)字的指標(biāo)的奇偶性取決于原始數(shù)字的位數(shù)是奇數(shù)還是偶數(shù)。您的代碼沒(méi)有考慮到這一點(diǎn)。
我們需要在開始時(shí)計(jì)算卡片的奇偶校驗(yàn),并通過(guò)遞歸cardSum()調(diào)用傳遞這個(gè)奇偶校驗(yàn),所以它會(huì)加倍正確的數(shù)字:
def cardSum(digits, parity):
if not digits:
return 0
digit, digits = int(digits[-1]), digits[:-1]
if len(digits) % 2 == parity:
digit *= 2
digit = digit // 10 + digit % 10
return digit + cardSum(digits, parity)
def cardCheck(cardSum, credit_card):
checksum = cardSum(credit_card, len(credit_card) % 2)
if checksum % 10 == 0:
if len(credit_card) == 15 and int(credit_card[0:2]) in [34, 37]:
print("AMEX")
elif len(credit_card) == 16 and int(credit_card[:2]) in range(50, 56):
print("MASTER CARD")
elif len(credit_card) in [13, 16] and int(credit_card[:1]) == 4:
print("VISA")
else:
print("INVALID")
else:
print("INVALID")
if __name__ == "__main__":
credit_card = input("Enter Credit Card Number: ")
if credit_card != "":
cardCheck(cardSum, credit_card)
我猜這是 AMEX 提出來(lái)的,因?yàn)樗且粋€(gè)奇數(shù)長(zhǎng)度的數(shù)字——您是否測(cè)試過(guò)任何其他發(fā)卡機(jī)構(gòu)的奇數(shù)長(zhǎng)度數(shù)字?
添加回答
舉報(bào)