Validate Credit Card Number

地址:http://www.codewars.com/kata/5418a1dd6d8216e18a0012b2/train/python


In this Kata, you will implement The Luhn Algorithm, which is used to help validate credit card numbers.


Given a positive integer of up to 16 digits, return true if it is a valid credit card number, and false if it is not.


Here is the algorithm:


If there are an even number of digits, double every other digit starting with the first, and if there are an odd number of digits, double every other digit starting with the second. Another way to think about it is, from the right to left, double every other digit starting with the second to last digit.


代码:

def validate(n):
    list = []
    while(n>10):
        list.append(n%10)
        n /= 10
    
    list.append(n)    
    sum = 0
    
    for i in range(0,len(list)):
        if( (len(list)%2 + i%2 ) % 2 == 0):
            list[i] *= 2
            if list[i] > 9:
                list[i] -= 9
        sum += list[i]

    if(sum%10 == 0):
        return 'true'
    else:
        return 'false'


你可能感兴趣的:(codewars)