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

Implements the Luhn test succinctly.

Python, 3 lines
1
2
3
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, 1 month ago  # | flag

Original wikipedia Python code is more readable than this recipe:

http://en.wikipedia.org/wiki/Luhn_algorithm#Implementation_of_standard_Mod_10

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