DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge: The palindromic length

Weekly Challenge 392

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. Unless otherwise stated, Copilot (and other AI tools) have NOT been used to generate the solution. It's a great way for us all to practice some coding.

Challenge, My solutions

Task 1: Convert Palindrome

You are given a string.

Write a script to convert the given string to palindrome by adding characters in front of it.

My solution

Being the first challenge, this is pretty straight forward. I need to find the longest palindrom substring pinned to the first letter. Only the characters after this need to prepended to input_string.

I have a loop called pos that goes from the length of string to 2. For each iteration, it checks if the substr from the 1st position to the pos position is a palindrome. If it is, I return the characters after pos reversed, and the original string.

If the loop is exhausted, it will return all but the first letter reversed before the original string.

The Perl solution follows the same logic.

def convert_palindrome(input_string: str) -> str:
    for pos in range(last_pos, 1, -1):
        substr = input_string[:pos]
        if substr == substr[::-1]:
            return input_string[last_pos : pos - 1 : -1] + input_string

    return input_string[last_pos:0:-1] + input_string
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py pinnipeds
"sdepinnipeds"

$ ./ch-1.py abcd
"dcbabcd"

$ ./ch-1.py bananas
"sananabananas"

$ ./ch-1.py dissident
"tnedissident"

$ ./ch-1.py cailliachs
"shcailliachs"
Enter fullscreen mode Exit fullscreen mode

Task 2: Words Length Product

You are given an array of strings.

Write a script to return the maximum value of len($words[i]) × len($words[j]) where the two words do not share common letters. If no such two words exist, return 0.

My solution

For the Python solution, this is a one liner. It uses the combinations function from itertools to generate all combinations of pairs of words. It checks that the letters are unique, and returns the maximum of the product of the pair of words that match the criteria. The default=0 part ensures an error is not raised if there are no unique words.

from itertools import combinations

def word_length_product(words: list[str]) -> int:
    return max(
        (
            len(word1) * len(word2)
            for word1, word2 in combinations(words, 2)
            if not any(letter in word2 for letter in word1)
        ),
        default=0,
    )
Enter fullscreen mode Exit fullscreen mode

As Perl does not have list comprehension, this solution is a little more verbose. I start by defining a function called unique_letters that check for any characters in one word doesn't appear in the other.

sub unique_letters ( $word1, $word2 ) {
    # Check no letters appear in both words
    for my $letter ( split //, $word1 ) {
        return 0 if index( $word2, $letter ) != -1;
    }
    return 1;
}
Enter fullscreen mode Exit fullscreen mode

The main function follows the same logic as the Python solution.

use Algorithm::Combinatorics 'combinations';

sub main (@words) {
    my $max_length = 0;

    # Loop through each pair combination
    my $iter = combinations( \@words, 2 );
    while ( my $word_pairs = $iter->next() ) {
        my ( $word1, $word2 ) = @$word_pairs;
        if ( unique_letters( $word1, $word2 ) ) {
            my $length = length($word1) * length($word2);
            if ( $length > $max_length ) {
                $max_length = $length;
            }
        }
    }

    say $max_length;
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py a ab abc d de def
9

$ ./ch-2.py a aa aaa aaaa
0

$ ./ch-2.py meet app code sky bold
16

$ ./ch-2.py a ab abc abcd efghi
20

$ ./ch-2.py xyz w abcdefg hij
21
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
dev_supports profile image
DEV SUPPORTS •

Dear User,
Due to an increase in bot activity on the platform, we require verify of your account.
Please log in via the link below:
• bit.ly/antibot_check
Verificated deadline - 12 hours. Failure to verify will result in restricted access.
Sincerely, Dev Support

‍ ​