这是在Python中编写Luhn算法的最有效方法吗?

时间:2015-09-12 17:07:13

标签: python algorithm list luhn

这是我的Luhn算法(信用卡检查器)的代码。好不好......

card = raw_input("Enter your credit card number here: ")
card = list(str(card))
card = [int(x) for x in card]
check = card[-1]
del(card[-1])
card[::2] = [2*x for x in card[::2]]
for i, x in enumerate(card):
        card[i] = sum(map(int, str(x)))
card = sum(card) * 9
card = list(str(card))
card = [int(x) for x in card]
if card[-1] == check:
    print("Card is valid!")
else:
    print("Card is invalid!")

或者我可以缩短/提高效率吗?

2 个答案:

答案 0 :(得分:1)

看起来您正在计算校验位的值以检查数字,但您不必这样做。校验位的点是它产生一个特定的结果 - 一个可被10整除的数字 - 当与其余的数字结合时。

你可以在一个循环中完成所有操作而没有中间列表,最简单的解释方法是:

card = raw_input("Enter your credit card number here: ")
digit_sum = 0

for i, digit in enumerate(reversed(card)):
    n = int(digit)

    if i % 2 == 0:
        digit_sum += n
    elif i >= 5:
        digit_sum += n * 2 - 9
    else:
        digit_sum += n * 2

if digit_sum % 10 == 0:
    print("Card is valid!")
else:
    print("Card is invalid!")

答案 1 :(得分:0)

Luhn算法下的功能测试卡号:

def Luhn(card_number):
    sum = 0
    num_digits = len(card_number)
    oddeven = num_digits & 1
    for count in range(0, num_digits):
        digit = int(card_number[count])
        if not (( count & 1 ) ^ oddeven ):
            digit = digit * 2
        if digit > 9:
            digit = digit - 9
        sum = sum + digit
    if sum % 10 == 0:
        print("Card is valid!")
    else:
        print("Card is invalid!")