DEV Community

Simon Green
Simon Green

Posted on

Double Luhn

Weekly Challenge 290

Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Double Exist

Tasks

You are given an array of integers, @ints.

Write a script to find if there exist two indices $i and $j such that:

  1. $i != $j
  2. 0 <= ($i, $j) < scalar @ints
  3. $ints[$i] == 2 * $ints[$j]

My solution

This seems relatively straight forward, but there is a massive gotcha that hopefully other Team PWC members also noticed. For this task, I loop through the list and see if a value that is twice its value exist.

However, if the value is '0' (and thus 0 × 2 = 0), I need to check that there were at least two zeros in the list.

def double_exists(ints: list) -> bool:

    for i in ints:
        if i * 2 in ints:
            if i != 0 or ints.count(0) > 1:
                return True

    return False
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 6 2 3 3
true

$ ./ch-1.py 3 1 4 13
false

$ ./ch-1.py 2 1 4 2
true

$ ./ch-1.py 1 3 0
false

$ ./ch-1.py 1 0 3 0
true
Enter fullscreen mode Exit fullscreen mode

Task 2: Luhn’s Algorithm

Task

You are given a string $str containing digits (and possibly other characters which can be ignored). The last digit is the payload; consider it separately. Counting from the right, double the value of the first, third, etc. of the remaining digits.

For each value now greater than 9, sum its digits.

The correct check digit is that which, added to the sum of all values, would bring the total mod 10 to zero.

Return true if and only if the payload is equal to the correct check digit.

My solution

I start this task by removing non-digit characters from the string, and turn the reversed string into a list of integers.

I then use the supplied formula, alternating between adding the value to count or multiplying it by two and removing 9. If the resulting count is divisible by 10, I return True, otherwise I return False.

def luhn_algorithm(s: str) -> bool:
    s = re.sub('[^0-9]', '', s)
    ints = [int(n) for n in s[::-1]]

    count = 0
    for pos, i in enumerate(ints):
        if pos % 2 == 1:
            i *= 2
            if i > 9:
                i -= 9
        count += i
    return count % 10 == 0
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py  17893729974
true

$ ./ch-2.py  "4137 8947 1175 5904"
true

$ ./ch-2.py "4137 8974 1175 5904"
false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)