在python中使用循环来配置信用卡号

时间:2015-09-18 18:01:46

标签: python python-2.7 python-3.x

我正在研究这个项目,我必须检查信用卡号是否有效。在这种情况下,我只需要一个8位数的信用卡(我知道这不是现实)。这是问题

信用卡号码的最后一位是校验位,可防止转录错误,例如单个数字错误或切换两位数字。以下方法用于验证实际的信用卡号,但为简单起见,我们将对8位数而不是16位的数字进行描述:

  

•从最右边的数字开始,形成彼此的总和   数字。例如,如果信用卡号是4358 9795,那么您   形成总和5 + 7 + 8 + 3 = 23.

     

•将前面未包含的每个数字加倍   步。添加结果数字的所有数字。例如,随着   上面给出的数字,从数字开始加倍   倒数第二个,yields 18 18 10 8。添加这些值中的所有数字   收益率1 + 8 + 1 + 8 + 1 + 0 + 8 = 27

     

•添加前两个步骤的总和。如果是最后一位数字   结果为0,该数字有效。在我们的例子中,23 + 27 = 50,所以   号码有效。

编写实现此算法的程序。用户应提供一个8位数字,您应该打印出该号码是否有效。如果它无效,您应该打印使其有效的校验位的值。

我必须使用循环来完成总和。但是,我不知道如何使用循环。

这是我的代码

# Credit Card Number Check. The last digit of a credit card number is the check digit,
# which protects against transcription errors such as an error in a single digit or
# switching two digits. The following method is used to verify actual credit card
# numbers but, for simplicity, we will describe it for numbers with 8 digits instead
# of 16:
#     Starting from the rightmost digit, form the sum of every other digit. For
#     example, if the credit card number is 43589795, then you form the sum
#     5 + 7 + 8 + 3 = 23.
#    Double each of the digits that were not included in the preceding step. Add #    all
#     digits of the resulting numbers. For example, with the number given above,
#     doubling the digits, starting with the next-to-last one, yields 18 18 10 8. Adding
#     all digits in these values yields 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27.
#     Add the sums of the two preceding steps. If the last digit of the result is 0, the
#     number is valid. In our case, 23 + 27 = 50, so the number is valid.
# Write a program that implements this algorithm. The user should supply an 8-digit
# number, and you should print out whether the number is valid or not. If it is not
# valid, you should print out the value of the check digit that would make the number
# valid.

    card_number = int(input("8-digit credit card number: "))

rights = 0
for i in card_number[1::2]:
   rights += int(i)

lefts = 0
for i in card_number[::2]:
   lefts += int(i)*2%10+int(i)*2/10

print card_number, (rights +lefts)/10

if remaining == 0:
    print("Card number is valid")

else:
    print("Card number is invalid")

    if digit_7 - remaining < 0:
        checkDigit = int(digit_7 + (10 - remaining))
        print("Check digit should have been:", checkDigit)

    else:
        checkDigit = int(digit_7 - remaining)
        print("Check digit should have been:", checkDigit)

4 个答案:

答案 0 :(得分:1)

如果我理解正确,你正在寻找这样的东西:

cards = ["43589795"]
for card_number in cards:  
     rights = sum(map(int, card_number[1::2]))
     lefts = sum(map(lambda x: int(x)*2%10+int(x)*2/10, card_number[::2])) # sum of doubled values
     print card_number, (rights +lefts)/10

没有map和lambda magic的相同解决方案:

rights = 0
for i in card_number[1::2]:
   rights += int(i)

lefts = 0
for i in card_number[::2]:
   lefts += int(i)*2%10+int(i)*2/10

print card_number, (rights +lefts)/10

关于你的问题的完整答案:

card_number = str(raw_input("8-digit credit card number: ")).replace(" ", "")

rights = 0
for i in card_number[1::2]:
   rights += int(i)

lefts = 0
for i in card_number[::2]:
   lefts += int(i)*2%10+int(i)*2/10

remaining = (rights +lefts)%10

digit_7 = int(card_number[-1]) # Last digit

if remaining == 0:
    print("Card number is valid")

else:
    print("Card number is invalid")

    if digit_7 - remaining < 0:
        checkDigit = int(digit_7 + (10 - remaining))
        print("Check digit should have been:", checkDigit)

    else:
        checkDigit = int(digit_7 - remaining)
        print("Check digit should have been:", checkDigit)

答案 1 :(得分:0)

以下是使用numpy的解决方案:

import numpy as np
d1=np.transpose(np.array(list('43589795'), dtype=np.uint8).reshape((4,2)))[0]*2
d2=np.transpose(np.array(list('43589795'), dtype=np.uint8).reshape((4,2)))[1]
if (np.sum(np.hstack([list(entry) for entry in d1.astype(str)]).astype(np.uint8))+np.sum(d2))%10==0:
    return "Validated"

在示例中,我们得到50,经过验证。

答案 2 :(得分:0)

从信用卡号码中修剪所有空格并尝试以下代码:

import itertools
sum = 0
for multiplicand,didgit in zip(itertools.cycle([2,1]), str(CREDIT_CARD_NUMBER)):
    result = multiplicand * int(didgit)
    sum += result / 10
    sum += result % 10
print "valid" if sum % 10 == 0 else "invalid"

上面的代码循环显示信用卡号,并同时计算两个总和。

答案 3 :(得分:0)

这是另一种可能的解决方案:

cc_number = input("8-digit credit card number: ").replace(" ", "")
total1 = 0
total2 = 0

for digit in cc_number[-1::-2]:
    total1 += int(digit)

for digit in cc_number[-2::-2]:
    total2 += sum(int(x) for x in str(int(digit)*2))

remainder = (total1 + total2) % 10

if remainder == 0:
    print("Card is valid!")
else:
    invalid_check_digit = int(cc_number[-1])

    if invalid_check_digit - remainder < 0:
        valid_check_digit = invalid_check_digit + (10 - remainder)
    else:
        valid_check_digit = invalid_check_digit - remainder

    print("Card is invalid - the correct check digit is {}".format(valid_check_digit))  

给你以下输出:

8-digit credit card number: 4358 9795
Card is valid!

或者:

8-digit credit card number: 4358 9794
Card is invalid - the correct check digit is 5