74. Luhn checksum
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:
- 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.
- If doubling gives more than 9, subtract 9: 7 doubles to 14, which counts as 5.
- 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
number = "79927398713"TrueExample 2
number = "79927398710"FalseExample 3
number = "0"FalseConstraints
numberhas 0 to 40 characters.
Submit also runs 14 more tests you can't see.
Practises Functions (lesson 16).
- Split the work into small functions: one cleans the text (
number.replace(" ", ""), then.isdigit()checks that only digits are left), another works out the total from a list of digits. - Going through
reversed(digits)withenumerate()makes "every second from the right" easy: those are the odd positions,i % 2 == 1. - Double those, subtract 9 from any result over 9, and add everything up. Doubling from the left instead only works when the number of digits is even.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.