使用Luhn算法(Luhn algorithm)校驗信用卡號的:
python
一、從卡號最右邊開始,由右向左,奇數位數字直接累加;
git
二、從卡號最右邊開始,由右向左,偶數位數字先乘以2(若是乘積爲兩位數,則將這兩位數再次累加或者將其減去9),再求和。
例如:10 = 1 + 0 = 1, 14 = 1 + 4 = 5 等價於 10 - 9 = 1, 14 - 9 = 5;
算法
三、將奇數位總和加上偶數位總和,結果對10取模爲0。函數
例如,卡號是:356827027232780
奇數位和=28
偶數位乘以2(有些要減去9)的結果求和=32。
spa
最後28+32=70 % 10 = 0,信用卡號校驗經過。code
def card_luhn_checksum(card_number): """經過 luhn mod-10校驗算法檢查信用卡號 """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(num_digits): digit = int(card_number[count]) if not (( count & 1) ^ oddeven): digit *= 2 if digit > 9: digit -= 9 sum += digit return (sum % 10) == 0
另外 本書的一句話函數修改有問題:orm
checksum = lambda a:(10 - sum([int(y)*[7,3,1][x%3] for x,y in enumerate(str(a)[::-1])])%10)%10
變態..ci