Last active
August 29, 2015 14:27
-
-
Save teknogeek/0b81284f8d522abba785 to your computer and use it in GitHub Desktop.
Super compressed version of Luhn's Algorithm in python
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
def luhnsChecksum(cardNumber): | |
#returns the actual digits in a string | |
def digitsOf(n): | |
return [int(d) for d in str(n) if d.isdigit()] | |
#get digits in card number | |
digits = digitsOf(cardNumber) | |
#get odd digits by incrementing backwards by -2 to -1 | |
oddDigits = digits[-1::-2] | |
#get even digits by incrementing backwards by -2 to -2 | |
evenDigits = digits[-2::-2] | |
#add all the digits together for a checksum | |
checksum = sum(oddDigits) | |
for d in evenDigits: | |
#for every number in the even digits, add the sum of 2x the digit to the checksum | |
checksum += sum(digitsOf(d * 2)) | |
#check whether or not it's evenly divisible by 10 and return whether it is or not | |
return checksum % 10 == 0 | |
if __name__ == "__main__": | |
#get the card number from user input | |
cardNumber = raw_input("Card number: ") | |
isValid = luhnsChecksum(cardNumber) | |
if isValid: | |
print "Valid" | |
else: | |
print "Invalid" |
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
def luhnChecksum(cardNumber): | |
getDigits = lambda n: [int(d) for d in str(n) if d.isdigit()] | |
digits = getDigits(cardNumber) | |
oddDigits, evenDigits = digits[-1::-2], digits[-2::-2] | |
checksum = sum(oddDigits) | |
for d in evenDigits: checksum += sum(getDigits(d * 2)) | |
return checksum % 10 == 0 | |
if __name__ == "__main__": print "Valid" if luhnChecksum(raw_input("Card number: ")) else "Invalid" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment