#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:
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.
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.
First solves only, ranked by stars and then time.