DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 258

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: Count Even Digits Number

Task

You are given a array of positive integers, @ints.

Write a script to find out how many integers have even number of digits.

My solution

This is relatively straight forward, and probably doesn't need an explanation for the people reading this post. The only thing worth mentioning is that we need to convert the integer to a string to get its length. The challenge specifically mentions positive integers only, so we don't need to worry about the length of negative numbers not being the number of digits it has.

def count_even_digits(ints: list) -> int:
    return sum(1 for i in ints if len(str(i)) % 2 == 0)
Enter fullscreen mode Exit fullscreen mode

Perl on the other hand doesn't care (except in a few rare circumstances) if the value is a string or number. grep in a scalar context will return the number of items that match the criteria.

sub main (@ints) {
    my $count = grep { length($_) % 2 == 0 } @ints;
    say $count;
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 10 1 111 24 1000
3

$ ./ch-1.py 111 1 11111
0

$ ./ch-1.py 2 8 1024 256
1
Enter fullscreen mode Exit fullscreen mode

Task 2: Sum of Values

Task

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

Write a script to find the sum of values whose index binary representation has exactly $k number of bits set.

My solution

This could also be done in a single line, but the code would be hard to understand. Therefore I took a more straight forward approach and use a for loop. For each position, if the number of bits set is $k I add that value to the total variable.

def sum_of_values(ints: list, k: int) -> int:
    total = 0

    for pos, value in enumerate(ints):
        if k == bin(pos).count('1'):
            total += value

    return total
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py 2 5 9 11 3 1
17

$ ./ch-2.py 2 5 9 11 3 2
11

$ ./ch-2.py 2 5 9 11 3 0
2
Enter fullscreen mode Exit fullscreen mode

Top comments (0)