Matching and zipping
Simon Green
Posted on February 18, 2024
Weekly Challenge 256
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.
Task 1: Maximum Pairs
Task
You are given an array of distinct words, @words
.
Write a script to find the maximum pairs in the given array. The words $words[i]
and $words[j]
can be a pair one is reverse of the other
My solution
For this task, I have a loop that takes the last value from the words
array and store it in the word
variable. I then see if its reverse is in the words
array, and increment the count if it is. I continue this until the original array is exhausted.
def count_pairs(words: list) -> int:
count = 0
while words:
word = words.pop()
if word[::-1] in words:
count += 1
return count
Examples
$ ./ch-1.py ab de ed bc
1
$ ./ch-1.py aa ba cd ed
0
$ ./ch-1.py uv qp st vu mn pq
2
Task 2: Merge Strings
Task
You are given two strings, $str1
and $str2
.
Write a script to merge the given strings by adding in alternative order starting with the first string. If a string is longer than the other then append the remaining at the end.
My solution
My solution will take any number of strings, be it one, two (as per the task) or more. Thankfully Python has the zip_longest function from itertools to make the task a one-liner.
def merge_strings(words: list) -> str:
return ''.join(''.join(s) for s in zip_longest(*words, fillvalue=''))
The zip_longest
function returns a iterable of tuples (with an empty string if one list is exhausted). The inner join turns this into a list of strings. The outer join turns this into a string.
The Perl solution follows a similar logic, and uses the mesh function from List::Util. The first lines converts an array of strings into an array of single characters. The mesh
function returns a flat array, so only a single join statement is required.
sub main (@words) {
my @arrays = map { [ split // ] } @words;
say join( '', mesh(@arrays) );
}
Examples
$ ./ch-2.py abcd 1234
a1b2c3d4
$ ./ch-2.py abc 12345
a1b2c345
$ ./ch-2.py abcde 123
a1b2c3de
Posted on February 18, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.