|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +""" |
| 4 | +Python Program using the Luhn Algorithm |
| 5 | +
|
| 6 | +This program uses the Luhn Algorithm, named after its creator |
| 7 | +Hans Peter Luhn, to calculate the check digit of a 10-digit |
| 8 | +"payload" number, and output the final 11-digit number. |
| 9 | +
|
| 10 | +To prove this program correctly calculates the check digit, |
| 11 | +the input 7992739871 should return: |
| 12 | +
|
| 13 | +Sum of all digits: 67 |
| 14 | +Check digit: 3 |
| 15 | +Full valid number (11 digits): 79927398713 |
| 16 | +
|
| 17 | +11/15/2021 |
| 18 | +David Costell (DontEatThemCookies on GitHub) |
| 19 | +""" |
| 20 | + |
| 21 | +# Input |
| 22 | +CC = input("Enter number to validate (e.g. 7992739871): ") |
| 23 | +if len(CC) < 10 or len(CC) > 10: |
| 24 | + input("Number must be 10 digits! ") |
| 25 | + exit() |
| 26 | + |
| 27 | +# Use list comprehension to split the number into individual digits |
| 28 | +split = [int(split) for split in str(CC)] |
| 29 | + |
| 30 | +# List of digits to be multiplied by 2 (to be doubled) |
| 31 | +tobedoubled = [split[1], split[3], split[5], split[7], split[9]] |
| 32 | +# List of remaining digits not to be multiplied |
| 33 | +remaining = [split[0], split[2], split[4], split[6], split[8]] |
| 34 | + |
| 35 | +# Step 1 |
| 36 | +# Double all values in the tobedoubled list |
| 37 | +# Put the newly-doubled values in a new list |
| 38 | +newdoubled = [] |
| 39 | +for i in tobedoubled: |
| 40 | + i = i*2 |
| 41 | + newdoubled.append(i) |
| 42 | +tobedoubled = newdoubled |
| 43 | + |
| 44 | +# Check for any double-digit items in the tobedoubled list |
| 45 | +# Splits all double-digit items into two single-digit items |
| 46 | +newdoubled = [] |
| 47 | +for i in tobedoubled: |
| 48 | + if i > 9: |
| 49 | + splitdigit = str(i) |
| 50 | + for index in range(0, len(splitdigit), 1): |
| 51 | + newdoubled.append(splitdigit[index:index+1]) |
| 52 | + tobedoubled.remove(i) |
| 53 | +newdoubled = [int(i) for i in newdoubled] |
| 54 | + |
| 55 | +# Unify all lists into one (luhnsum) |
| 56 | +luhnsum = [] |
| 57 | +luhnsum.extend(tobedoubled) |
| 58 | +luhnsum.extend(newdoubled) |
| 59 | +luhnsum.extend(remaining) |
| 60 | + |
| 61 | +# Output |
| 62 | +print("Final digit list:", luhnsum) |
| 63 | +print("Sum of all digits:", sum(luhnsum)) |
| 64 | +checkdigit = 10 - sum(luhnsum) % 10 |
| 65 | +print("Check digit:", checkdigit) |
| 66 | +finalcc = str(CC)+str(checkdigit) |
| 67 | +print("Full valid number (11 digits):", finalcc) |
| 68 | +input() |
0 commit comments