/python/luhn/luhn.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Luhn(object):
    def __init__(self, digits):
        self._digits = map(int, str(digits))

    def addends(self):
        """
        Return list of transformed digits as per the Luhn formula -
        counting backwards from the end, double the value of
        every second digit, then subtract 9 if the result is 10 or more.
        """
        def transform_digit(i, d):
            """
            i is the reverse index of the digit
            d is the digit
            """
            if i % 2 == 1:
                if d < 5:
                    # double the digit
                    return (d * 2)
                else:
                    # d >= 5 will multiply up to 10 or more, so subtract 9
                    return (d * 2) - 9
            else:
                return d

        # Digits are counted from the end of the string here -
        # so process it in reverse order, and reverse the result.
        return [transform_digit(i, d)
                for i, d in enumerate(self._digits[::-1])][::-1]

    def checksum(self):
        """
        Return Luhn checksum for the number
        """
        return sum(self.addends()) % 10

    def is_valid(self):
        """
        Return true if number is valid as per the Luhn formula
        """
        return self.checksum() == 0

    @classmethod
    def create(cls, digits):
        """
        Add a check digit to make a number valid as per the Luhn formula
        Return the original number plus check digit
        """
        # Calculate the checksum when a zero is added to the end,
        with_zero = digits * 10
        zero_checksum = Luhn(with_zero).checksum()

        # Adjust the final digit to ensure a zero checksum.
        return with_zero + ((10 - zero_checksum) % 10)

Comments


You're not logged in right now. Please login via GitHub to comment