Screen Pasted Card Numbers: Format, Issuer Prefix and Luhn
StringsAuto-graded · 24 test casesLast updated
Filter strings by a character and length rule, an issuer-prefix range and the Luhn checksum, returning the original text of each valid entry in input order.
A banking app lets customers create disposable card numbers. Before a number is stored, the backend screens the text a user typed or pasted. You are given a list of such strings and must return the ones that pass every screening rule.
Screening rules
A string is acceptable only if it satisfies all three rules.
- Format. Remove every space (
" ") and every hyphen ("-") from the string. What remains must consist only of decimal digit characters (characters for which Python'sstr.isdecimal()is true, each read as its numeric value withint), and there must be exactly 16 of them. Any other leftover character, such as a letter, tab, dot or other symbol, makes the string unacceptable. An empty result is unacceptable. - Checksum (Luhn). Take the 16 digits and walk from the rightmost digit toward the left. The rightmost digit is position 1 and is not doubled. Double the digits at positions 2, 4, 6, and so on. If a doubled value is greater than 9, subtract 9 from it. Add up all the resulting values. The total must be divisible by 10.
- Issuer range. The first two digits, read as a two-digit number, must be between 51 and 55, inclusive.
Task
Implement a function that takes a list of strings and returns a new list containing only the acceptable strings. Each returned string must be the original, unmodified text, including its spaces and hyphens. Keep the same relative order as in the input. Duplicate inputs are each judged independently and each kept if acceptable. If nothing is acceptable, return an empty list.
Constraints
0 <= len(entries) <= 10^4- Each string may be empty and may contain arbitrary characters; its length is at most 100.
- Only the three rules above decide acceptance; there are no other hidden conditions.
- Spaces and hyphens may appear anywhere, in any quantity, as long as exactly 16 digits remain.
Examples
Example 1
Input: filter_disposable_cards(['5342 1987 0012 3456', '5248-4850-6950-6990', '4991 3944 1177 1512', '5518 2000 3344 5560 1', '5351 0273 4646 8695', '5266 1111 2222 333O'])
Output: ['5342 1987 0012 3456', '5248-4850-6950-6990']
Hints
Hint 1
Strip spaces and hyphens first, then check that what is left is all digits and has length exactly 16.
Hint 2
For the checksum, index the digits from the right (for example by reversing the string) so the parity of the position does not depend on where you started counting.
Hint 3
Test the issuer range with a two-digit integer comparison, and append the original string (not the cleaned one) to the result when all three rules pass.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Process each string independently and keep it only if it clears three checks:
- Format. Remove spaces and hyphens, then require that exactly 16 characters remain and that all of them are decimal digits. Checking the length first is cheap and also rejects the empty case.
- Issuer range. Convert the first two digits to an integer and require
51 <= prefix <= 55. A single chained comparison avoids the classic mistake of combining the two bounds with the wrong logical operator. - Luhn checksum. Enumerate the digits from the right. The digit at index 0 (rightmost) is left alone, and digits at odd indices (1, 3, 5, ...) are doubled, with 9 subtracted when the result exceeds 9. The sum must be divisible by 10.
Counting from the right is what the checksum rule requires. Counting from the left would double the other half of the digits for a 16-digit number and give wrong answers.
Strings that pass are appended unchanged, so the output keeps the original text and the input order.
Why it is correct
Each rule is a direct transcription of the specification, and a string is kept only when all three hold. Failing any one check skips the string, so no unacceptable string is returned. Every acceptable string reaches the append, so none is lost. Appending in iteration order preserves ordering.
Complexity
Each string has at most 100 characters and is scanned a constant number of times, so the total time is O(N * L) for N strings of length at most L. Extra space is O(L) per string for the cleaned digits, plus the output list.
Reference solution
from typing import List
def filter_disposable_cards(entries: List[str]) -> List[str]:
result = []
for text in entries:
# Rule 1: after stripping spaces/hyphens, exactly 16 decimal digits
digits = text.replace(" ", "").replace("-", "")
if len(digits) != 16 or not digits.isdecimal():
continue
# Rule 3: issuer prefix 51..55
if not (51 <= int(digits[:2]) <= 55):
continue
# Rule 2: Luhn checksum, counting from the right
total = 0
for pos, ch in enumerate(reversed(digits)):
d = int(ch)
if pos % 2 == 1:
d *= 2
if d > 9:
d -= 9
total += d
if total % 10 == 0:
result.append(text)
return result