Luhn公式信用卡验证代码时好时坏,请求问题排查
Hey there! Let's break down why your code works for some card numbers but fails for others—this is a common mistake with how you're tracking digit positions.
The Root Cause
The bug lies in this line of your loop:
if card_number.index(i) % 2 != 0:
The list.index(i) method returns the first occurrence of the value i in the list, not the index of the current element you're iterating over. When your reversed card number has duplicate digits (like multiple 3s or 9s in 4916092180934319), this means you're using the wrong index to decide whether to multiply the digit by 2.
Example of the Issue
Take your problematic card number 4916092180934319:
- Reversed, it becomes
['9','1','3','4','3','9','0','8','1','2','9','0','6','1','9','4'] - When you loop to the second
3(actual index 4),card_number.index('3')returns 2 (the first3's index) - This makes your code treat it as an even index (no multiplication), but it should be an odd index (needs multiplying by 2)
- This error cascades through your sum calculation, leading to the incorrect "invalid" result
Why the Other Card Number Works
Your valid test case 49927398716 works purely by coincidence. The duplicate digits in its reversed form happen to be in positions where their first occurrence's index has the same even/odd parity as their actual current index. So the calculation accidentally produces the right sum, even though the logic is flawed.
Fix Direction
To resolve this, you need to track the actual index of each element as you iterate, instead of using index(). The standard way to do this in Python is with the enumerate() function, which gives you both the index and the value in each loop iteration.
内容的提问来源于stack exchange,提问作者Amirtha

