Welcome, guest | Sign In | My Account | Store | Cart

Implements the Luhn test succinctly.

Python, 3 lines
def luhn(n):
    r = [int(ch) for ch in str(n)][::-1]
    return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0

This solution was chosen as I had to factor the convoluted wikipedia description to find a better way to calculate the answer. I prefer this description, posted on Rosetta Code.

1 comment

Denis Barmenkov 14 years, 2 months ago  # | flag

Original wikipedia Python code is more readable than this recipe:


Created by Paddy McCarthy on Mon, 1 Mar 2010 (MIT)
Python recipes (4591)
Paddy McCarthy's recipes (10)

Required Modules

  • (none specified)

Other Information and Tasks