![](/img/trans.png)
[英]Python function to check if credit card number is a valid number using for loops
[英]Using loops in python to configure credit card number
我正在從事這個項目,我必須檢查信用卡號是否有效。 在這種情況下,我只需要一張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)
如果我理解正確,那么您正在尋找這樣的東西:
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
沒有地圖和lambda魔術的相同解決方案:
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)
這是使用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個經過驗證的結果。
修剪信用卡號中的所有空格,然后嘗試以下代碼:
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"
上面的代碼遍歷信用卡號,並同時計算兩個總和。
這是另一種可能的解決方案:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.