DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge: Validating Words

Weekly Challenge 353

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: Max Words

Task

You are given an array of sentences.

Write a script to return the maximum number of words that appear in a single sentence.

My solution

There was a error in the original example. Like a good hacker, I raised a pull request to fix it.

This seems pretty straight forward. I strip any leading and trailing white space, and then count the words in the string (separate the sentence by any white space). I have a variable called max_words that has a running total of the maximum word count so far.

def max_words(sentences: list) -> int:
    max_words = 0

    for sentence in sentences:
        word_count = len(sentence.strip().split())
        if word_count > max_words:
            max_words = word_count


    return max_words
Enter fullscreen mode Exit fullscreen mode

The Perl code follows the same logic. It has a Perl-ism that using a scalar for an array (using the split function in this case) will assign the number of elements to the variable.

sub main (@sentences) {
    my $max_words = 0;

    foreach my $sentence (@sentences) {
        $sentence =~ s/^\s+|\s+$//g;

        my $word_count = split( /\s+/, $sentence );
        if ( $word_count > $max_words ) {
            $max_words = $word_count;
        }
    }

    say $max_words;
}
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py "Hello world" "This is a test" "Perl is great"
4

$ ./ch-1.py "Single"
1

$ ./ch-1.py "Short" "This sentence has seven words in total" "A B C" "Just four words here"
7

$ ./ch-1.py "One" "Two parts" "Three part phrase" ""
3

$ ./ch-1.py "The quick brown fox jumps over the lazy dog" "A" "She sells seashells by the seashore" "To be or not to be that is the question"
10
Enter fullscreen mode Exit fullscreen mode

Task 2: Validate Coupon

Task

You are given three arrays, @codes, @names and @status.

Write a script to validate codes in the given array.

A code is valid when the following conditions are true:

  • codes[i] is non-empty and consists only of alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).
  • names[i] is one of the following four categories: "electronics", "grocery", "pharmacy", "restaurant".
  • status[i] is true.

Return an array of booleans indicating validity: output[i] is true if and only if codes[i], names[i] and status[i] are all valid.

My solution

For input from the command line, I take triplets of a code, a name and a status.

For this task, I start with an empty list (array in Perl) called output. I then have a loop - with the variable i - that starts at 0 to one less than the length of the list.

For each iteration I start by setting the is_valid variable to True (the string true in Perl). I check that the specified criteria are met and set the is_valid variable to False if it isn't. Finally I append the is_valid variable to the output list.

def validate_codes(codes: list, names: list, status: list) -> list:
    output = []

    for i in range(len(codes)):
        is_valid = True
        if re.match(r'^[A-Za-z0-9_]+$', codes[i]) is None:
            is_valid = False
        elif names[i] not in ["electronics", "grocery", "pharmacy", "restaurant"]:
            is_valid = False
        elif status[i].lower() == "false":
            # The status is a string of 'true' or 'false', not boolean type.
            is_valid = False
        elif status[i].lower() != 'true':
            raise ValueError(f"Status must be 'true' or 'false', not '{status[i].lower()}'")
        output.append(is_valid)

    return output
Enter fullscreen mode Exit fullscreen mode

The Perl solution follows the same logic.

Examples

$ ./ch-1.py A123 electronics true B_456 restaurant false C789 electronics true D@1 pharmacy true E123 grocery true
1

$ ./ch-2.py A123 electronics true B_456 restaurant false C789 electronics true D@1 pharmacy true E123 grocery true
[True, False, True, False, True]

$ ./ch-2.py Z_9 pharmacy true AB_12 electronics true G01 grocery false X99 electronics true test unknown true
[True, True, False, True, False]

$ ./ch-2.py _123 restaurant true 123 electronics true "" electronics false Coupon_A pharmacy true Alpha grocery true
[True, True, False, True, True]

$ ./ch-2.py ITEM_1 electronics true ITEM_2 electronics true ITEM_3 grocery true ITEM_4 grocery true
[True, True, True, True]

$ ./ch-2.py CAFE_X restaurant true ELEC_100 electronics true FOOD_1 grocery true DRUG_A pharmacy true ELEC_99 electronics false
[True, True, True, True, False]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)