KatInterview

Screen Pasted Card Numbers: Format, Issuer Prefix and Luhn

StringsAuto-graded · 24 test cases
EasyAuto-gradedStringsstringsvalidationluhn

Last 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.

  1. Format. Remove every space (" ") and every hyphen ("-") from the string. What remains must consist only of decimal digit characters (characters for which Python's str.isdecimal() is true, each read as its numeric value with int), 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.
  2. 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.
  3. 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.