这是在Python中编写Luhn算法的最有效方法吗?
Is this the most efficient way to write the Luhn algorithm in Python?
这是我的 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!")
或者我可以shorter/more提高效率吗?
看起来您正在计算校验位的值来检查数字,但您不必这样做。校验位的要点在于,当与其余数字组合时,它会产生一个特定的结果——一个可以被 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 n >= 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!")
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!")
这是我的 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!")
或者我可以shorter/more提高效率吗?
看起来您正在计算校验位的值来检查数字,但您不必这样做。校验位的要点在于,当与其余数字组合时,它会产生一个特定的结果——一个可以被 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 n >= 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!")
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!")