DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 230

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: Separate Digits

Task

You are given an array of positive integers.

Write a script to separate the given array into single digits.

My solution

Two relatively straight forward tasks this week, so doesn't really need much explanation. For this task I can treat the integers as strings. Iterating a string will produce the individual characters. I then use a double for loop to flatten this to a single list.

solution = [ digit for i in ints for digit in i]
Enter fullscreen mode Exit fullscreen mode

In Perl, I use the split method to get the individual digits of the number, and map to achieve this for all numbers.

my @solution = ( map { split // } @ints );
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py 1 34 5 6
(1, 3, 4, 5, 6)

$ ./ch-1.py 1 24 51 60
(1, 2, 4, 5, 1, 6, 0)
Enter fullscreen mode Exit fullscreen mode

Task 2: Count Words

Task

You are given an array of words made up of alphabetic characters and a prefix.

Write a script to return the count of words that starts with the given prefix.

My solution

For this task, I pop the last item of the list, and assign this to the prefix variable. I then use the startswith() method on the string to count the number of words that start with the prefix.

solution = sum(1 for word in words if word.lower().startswith(prefix.lower()))
Enter fullscreen mode Exit fullscreen mode

For the Perl solution, we can use the grep function to find words that start with the prefix.

    my @solution = grep { substr( lc $_, 0, $len ) eq lc($prefix) } @words;
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py pay attention practive attend at
2

$ ./ch-2.py janet julia java javascript ja
3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)