Skip to content

Instantly share code, notes, and snippets.

@saifat29
Created October 1, 2021 20:49
Show Gist options
  • Save saifat29/f9e30b48575b32f552ff2d5abc051ca4 to your computer and use it in GitHub Desktop.
Save saifat29/f9e30b48575b32f552ff2d5abc051ca4 to your computer and use it in GitHub Desktop.
from itertools import product
checker = [
"2", "1", "2", "1", "2", "1", "2", "1",
"2", "1", "2", "1", "2", "1", "2", "1"
]
def sum_card_digits(card_num):
total = 0
for n in card_num:
total += int(n)
return total
def valid_card(cards):
print("Validating...")
result = []
for card in cards:
if luhn_valid(card) and (int(card) % 123457) == 0:
result.append(card)
return result
def build_card_nums(card_num, missing_digits, perms):
print("Building numbers...")
result = []
for perm in perms:
p = "".join(map(str, perm))
c = card_num.replace("*"*missing_digits, p)
result.append(c)
return result
def possible_perms(init_sum, missing_digits):
print("Generating permutations...")
result = []
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for p in product(x, repeat=missing_digits):
result.append(p)
return result
def luhn_sum(num):
total = 0
for i, n in enumerate(num):
if n == "*":
continue
cost = int(n) * int(checker[i])
if cost > 9:
cost -= 9
total += cost
return total
def luhn_valid(num):
total = luhn_sum(num)
if total % 10 == 0:
return True
return False
def main():
card_num = "543210******1234"
missing_digits = card_num.count("*")
init_sum = luhn_sum(card_num)
perms = possible_perms(init_sum, missing_digits)
possible_cards = build_card_nums(card_num, missing_digits, perms)
result = valid_card(possible_cards)
print("--------------------------")
print("Found {} valid card(s)".format(len(result)))
print("Card Number:{}".format(result))
print("--------------------------")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment