Skip to content

Instantly share code, notes, and snippets.

@dhaninugraha
Last active December 13, 2023 13:10
Show Gist options
  • Save dhaninugraha/83a5b9d95501c226e8ece34ae6a65fc2 to your computer and use it in GitHub Desktop.
Save dhaninugraha/83a5b9d95501c226e8ece34ae6a65fc2 to your computer and use it in GitHub Desktop.
python - Luhn's algorithm
def luhn(card_no):
card_no = str(card_no)
pp = "INVALID"
card_specs = {
"AMEX": {
"prefix": ["34", "37"],
"max_len": [15]
},
"VISA": {
"prefix": ["4"],
"max_len": [13, 16]
},
"MASTERCARD": {
"prefix": [str(i) for i in range(51, 56)],
"max_len": [16]
}
}
for card, spec in card_specs.items():
if len(card_no) in spec["max_len"]:
for prefix in spec["prefix"]:
if card_no[:len(prefix)] == prefix:
pp = card
break
if pp == "INVALID":
print(pp)
return
multip_2 = []
odd = []
for i, d in enumerate(card_no[::-1]):
if (i+1) % 2 == 0:
multip_2.append(str(int(d) * 2))
else:
odd.append(int(d))
res = sum([int(c) for d in multip_2 for c in d] + odd)
if res % 10 != 0:
pp = "INVALID"
print(pp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment