DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 261

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: Element Digit Sum

Task

You are given an array of integers, @ints.

Write a script to evaluate the absolute difference between element and digit sum of the given array.

My solution

Given that Perl doesn't care (most of the time) between numbers and strings, this is one of those challenges that is easier to do in Perl.

my $element_sum = sum(@ints);
my $digit_sum   = sum( map { split // } @ints );
say abs( $element_sum - $digit_sum );
Enter fullscreen mode Exit fullscreen mode

The sum function comes from List::Util. The first line gets the sum of the elements. The second line splits the integers by the digits and calculates the sum. The final line calculates and display the absolute difference.

My Python solution is as follows

def element_digit_sum(ints: list) -> int:
    element_sum = sum(ints)
    digit_sum = sum(int(i) for s in map(str, ints) for i in s)
    return abs(element_sum - digit_sum)
Enter fullscreen mode Exit fullscreen mode

It follows the same logic and the Perl code. The second line does the following

  • map(str, ints) turns the list of integers into a generator of strings
  • for s in iterates over the generator
  • for i in s iterates over each character in the string
  • int(i) turns that character into an integer
  • sum() turns the list of integers into a sum of the values

Examples

$ ./ch-1.py 1 2 3 45
36

$ ./ch-1.py 1 12 3
9

$ ./ch-1.py 1 2 3 4
0

$ ./ch-1.py 236 416 336 350
1296
Enter fullscreen mode Exit fullscreen mode

Task 2: Multiply by Two

Task

You are given an array of integers, @ints and an integer $start..

Write a script to do the following:

  1. Look for $start in the array @ints, if found multiply the number by 2
  2. If not found stop the process otherwise repeat

In the end return the final value.

My solution

This seems relatively straight forward. I keep multiplying the start by two until the value does not appear in the list. For performance, I could have converted the list into a set (hash in Perl), as checking in-ness (is that a word?) is faster that way. However, we are dealing with a small list, so it is not required.

def multiple_by_two(ints: list, start: int) -> int:
    solution = start
    while solution in ints:
        solution *= 2

    return solution
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 5 3 6 1 12 3
24

$ ./ch-2.py 1 2 4 3 1
8

$ ./ch-2.py 5 6 7 2
2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)