Test validity of any credit card number using the LUHN method (mod 10). Starting at the last digit and moving backwards, you add up every other digit. Then, you double the left-out digits, and add the digits of these results to the original sum. If this satisfies sum mod 10 == 0 then the card is valid.
This is also explained at http://www.beachnet.com/~hstiles/cardtype.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import re
def validate(number):
'Validates any credit card number using LUHN method'
number = str(number)
re.sub(r' ', '', number)
count = 0
for i in range(len(number)):
val = int(number[-(i+1)])
if i % 2 == 0:
count += val
else:
count += int(str(2 * val)[0])
if val > 5:
count += int(str(2 * val)[1])
if count % 10 == 0:
return True
else:
return False
|
Some constructive criticism:
re.sub() returns the altered string. You have to assign it to a variable.
Do not use regular expressions where str.replace() works fine:
Don't do math with strings. Floor division (//) and remainder (%) work well for this.
Have a look at list comprehensions.
My version:
or even:
I've practise a more short version with credit card number in string :