Editor

Luhn Checksum

#251 · Codes and ciphers · Beginner · 40 XP · about 8 min

The last digit of a bank card number is a check digit: it is chosen so that the whole number passes the Luhn test, and most typing mistakes make it fail. The Luhn test works like this:

  • starting from the rightmost digit and moving left, double every second digit: the second from the right, the fourth from the right, and so on (the rightmost digit itself is not doubled);
  • if doubling a digit gives a number greater than 9, subtract 9 from it;
  • add up all the digits, the changed ones and the unchanged ones;
  • the number passes when that total is a multiple of 10.

Write luhn_valid(number) that takes the number as a string and returns True if it passes the test and False otherwise. Spaces in the string are ignored. A string that holds any other character that is not a digit is not valid, and neither is one with fewer than two digits.

Examples

luhn_valid("059")                  # returns True
luhn_valid("095")                  # returns False
luhn_valid("5203 8491 7260 4534")  # returns True
luhn_valid("5203 8491 7260 4543")  # returns False

For "059": from the right, 9 stays 9, then 5 is doubled to 10, which becomes 1, then 0 stays 0. The total is 9 + 1 + 0 = 10, a multiple of 10. The last example swaps two neighbouring digits of a valid number, a classic typing slip, and the test catches it.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.