Created
October 4, 2017 16:36
-
-
Save itdaniher/ae8f3421e5e4ae158a3a9c5497c70003 to your computer and use it in GitHub Desktop.
luhn_tester.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
import random | |
def luhn_residue(digits): | |
return sum(sum(divmod(int(d)*(1 + i%2), 10)) | |
for i, d in enumerate(digits[::-1])) % 10 | |
def get_valid_luhn(N, preamble = ""): | |
part = preamble+''.join(str(random.randrange(0,9)) for _ in range(N-1-len(preamble))) | |
res = luhn_residue('{}{}'.format(part, 0)) | |
return '{}{}'.format(part, -res%10) | |
if __name__ == "__main__": | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument("digits", type=int) | |
parser.add_argument("preamble", default="", nargs="?") | |
args = parser.parse_args() | |
if len(args.preamble) == args.digits: | |
input_luhn = args.preamble | |
given_digit = input_luhn[-1] | |
input_luhn = input_luhn[0:-1] + '0' | |
check_digit = str(-luhn_residue(input_luhn)%10) | |
assert check_digit == given_digit | |
print('valid') | |
else: | |
output = get_valid_luhn(args.digits, args.preamble) | |
assert len(output) == args.digits | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment