DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 240

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: Acronym

Task

You are given an array of strings and a check string.

Write a script to find out if the check string is the acronym of the words in the given array.

My solution

Both of these weeks solutions are one-liners so there isn't much to explain. For this task, I take the first each of each words and do a case insensitive comparison with the acronym.

Both the Python and Perl solutions use the map function to get the first letter, and perform a join to calculate the first_letters variable.

Python:

first_letters = ''.join(map(lambda w: w[0], words))
print('true' if first_letters.lower() == acronym.lower() else 'false')
Enter fullscreen mode Exit fullscreen mode

Perl:

my $first_letters = join( '', map { substr( $_, 0, 1 ) } @words );
say lc($first_letters) eq lc($acronym) ? 'true' : 'false';
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py Perl Python Pascal ppp
true

$ ./ch-1.py Perl Raku rp
false

$ ./ch-1.py Oracle Awk C oac
true
Enter fullscreen mode Exit fullscreen mode

Task 2: Build Array

Task

You are given an array of integers.

Write a script to create an array such that new[i] = old[old[i]] where 0 <= i < new.length.

My solution

Not much to this task. Generate a list based on the specifications in the task.

Although it might be argued that this is a trick task. If read at face value. new.length is 0, and thus an empty list (array in Perl) would be the 'correct' solution :)

Python:

solution = [ ints[ints[i]] for i in range(len(ints))]
print(*solution, sep=', ')
Enter fullscreen mode Exit fullscreen mode

Perl:

my @solution = ( map { $ints[ $ints[$_] ] } ( 0 .. $#ints ) );
say join ', ', @solution;
Enter fullscreen mode Exit fullscreen mode

Examples

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

$ ./ch-2.py 5 0 1 2 3 4
4, 5, 0, 1, 2, 3
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay