THE WEEKLY CHALLENGE - 230

https://theweeklychallenge.org/blog/perl-weekly-challenge-230/

Table of Contents

Task 1 - Separate Digits

I took part in Perl Weekly Challenge 230 and solved some fun tasks in Perl and Python. Let me walk through my solutions and thought process.

The first task was to take an array of integers, and separate each element into its individual digits. For example, given the input:

[1, 34, 5, 6]

The output should be:

[1, 3, 4, 5, 6]

To separate an array of positive integers into single digits, I used the map function in Perl and a list comprehension in Python. The map function applies a function to each element of an array, while a list comprehension creates a new list by applying an expression to each element of an existing list. I also used the split function in Perl to split each integer into its individual digits.

My initial Perl solution was:

my @ints = (1, 34, 5, 6);
my @digits = map { split // } @ints;
print "@digits\n";

And similarly in Python:

ints = [1, 34, 5, 6]
digits = [int(d) for d in ''.join(map(str, ints))]
print(digits)

Task 2 - Counting Words

The second task was to count how many words in a given list start with a specific prefix string. For example:

Words: ["pay", "attention", "practice", "attend"]
Prefix: "at"

Output: 2

Since "attention" and "attend" match the prefix, the count is 2.

To count the number of words in an array that start with a given prefix, I used regular expressions in Perl and the startswith method in Python. Regular expressions are patterns used to match character combinations in strings, while the startswith method checks if a string starts with a given prefix. I also used functions to encapsulate our code and make it reusable.

The code in Perl:

use strict;
use warnings;
use Test::More;
use feature 'say';

sub count_words {
    my ($prefix, @words) = @_;
    my $count = 0;
    foreach my $word (@words) {
        if ($word =~ /^$prefix/) {
            $count++;
        }
    }
    return $count;
}

# Test 1
my $prefix1 = "at";
my @words1 = ("pay", "attention", "practice", "attend");
is(count_words($prefix1, @words1), 2, 'Test 1: Counting words with prefix');

# Test 2
my $prefix2 = "ja";
my @words2 = ("janet", "julia", "java", "javascript");
is(count_words($prefix2, @words2), 3, 'Test 2: Counting words with prefix');

done_testing();

And a similar solution in Python:

from typing import List

def count_words(prefix: str, words: List[str]) -> int:
    count = 0
    for word in words:
        if word.startswith(prefix):
            count += 1
    return count

# Test 1
prefix1 = "at"
words1 = ["pay", "attention", "practice", "attend"]
assert count_words(prefix1, words1) == 2

# Test 2
prefix2 = "ja"
words2 = ["janet", "julia", "java", "javascript"]
assert count_words(prefix2, words2) == 3