Drill

ProblemsPython › payments

Luhn check a card number

mediumpaymentsPython

Before a card ever reaches the payment gateway, the checkout runs the Luhn checksum so an obvious typo is caught in the browser.

luhn_valid(digits: string) → bool

Solve it in the editor →

Where you start

def luhn_valid(digits: str) -> bool:
    

Worked examples

CallResult
luhn_valid("79927398713")True
luhn_valid("79927398710")False
luhn_valid("4111 1111 1111 1111")True
luhn_valid("4111-1111-1111-1112")False

Hint

Strip the formatting into a clean string first. Then walk it backwards with an index so "every second" is easy to say.

Reference solution in Python
def luhn_valid(digits: str) -> bool:
    clean = ''
    for c in digits:
        if c in ' -':
            continue
        if not c.isdigit():
            return False
        clean += c
    if len(clean) < 2:
        return False
    total = 0
    for i, c in enumerate(reversed(clean)):
        d = int(c)
        if i % 2 == 1:
            d *= 2
            if d > 9:
                d -= 9
        total += d
    return total % 10 == 0

The same problem in another language

More payments problems in Python