50 XP

74. Luhn checksum

Intermediate math strings

Many identification numbers, bank card numbers among them, end in a check digit chosen so that the whole number passes the Luhn checksum. A single mistyped digit, or two neighbouring digits swapped, almost always makes it fail, so a form can catch the mistake before sending anything.

The check goes like this, on the digits alone:

  1. Starting from the rightmost digit and moving left, double every second digit: the second from the right, the fourth, and so on. The rightmost digit is not doubled.
  2. If doubling gives more than 9, subtract 9: 7 doubles to 14, which counts as 5.
  3. Add up all the digits, the changed and the unchanged ones. The number passes if the total ends in 0.

Write a function is_valid(number) that takes the number as a string and returns True if it passes, or False if it doesn't:

  • Spaces may appear anywhere and are ignored, so "4111 1111 1111 1111" is fine.
  • Any other character that isn't a digit makes the number invalid.
  • A number needs at least 2 digits; anything shorter is invalid.

Example 1

Inputnumber = "79927398713"
OutputTrue
ExplanationThe digits' total, with doubling, is 70.

Example 2

Inputnumber = "79927398710"
OutputFalse
ExplanationThe last digit changed: the total is 67.

Example 3

Inputnumber = "0"
OutputFalse
ExplanationA single digit is too short.

Constraints

  • number has 0 to 40 characters.

Submit also runs 14 more tests you can't see.

Practises Functions (lesson 16).

Code
def is_valid(number):
    """Check a number with the Luhn checksum.

    number: str, digits and spaces (other characters make
        it invalid)
    Returns: bool, True if it has 2 or more digits and
        passes the checksum
    """
    # Write your code here
    pass