Skip to content

Instantly share code, notes, and snippets.

@terraboops
Created January 30, 2017 05:30
Show Gist options
  • Save terraboops/ccea51650487f7a6db9a8806b7d1be5c to your computer and use it in GitHub Desktop.
Save terraboops/ccea51650487f7a6db9a8806b7d1be5c to your computer and use it in GitHub Desktop.
Randomly find a number which satisfies Luhn's algorithm
#!/usr/bin/env python
import random
def digits_of(number):
return [int(i) for i in str(number)]
def luhn_checksum(card_number):
digits = digits_of(card_number)
odd_digits = digits[-1::-2]
even_digits = digits[-2::-2]
total = sum(odd_digits)
for digit in even_digits:
total += sum(digits_of(2 * digit))
return total % 10
def is_luhn_valid(card_number):
return luhn_checksum(card_number) == 0
def make_random_num():
return ''.join(map(lambda x: str(random.randrange(0,9)),range(16)))
random_num = make_random_num()
while (not is_luhn_valid(random_num)):
print "Invalid: " + random_num
random_num = make_random_num()
print "Valid: " + random_num
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment