DEV Community

Simon Green
Simon Green

Posted on

Finding things

Weekly Challenge 273

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: Percentage of Character

Task

You are given a string, $str and a character $char.

Write a script to return the percentage, nearest whole, of given character in the given string.

My solution

Let's talk about 'nearest integer', and rounding. When you go to supermarket and something costs 45¢, you generally will be charged 50¢ if paying with cash and your currency doesn't have a 5¢ coin. This is called cash rounding, and probably what you were taught at school.

Python uses bankers rounding, where numbers are rounded to the nearest even. Therefore both 35¢ and 45¢ would be rounded to 40¢, while the sum remains the same (80¢).

This task is ambiguous as it does not mention which method to use when the percentage is a half figure. I've used the cash rounding method, as the sixth example supports this.

For this task, I take the number of characters that occur in the length of the string divided by the length of the string multiplied by 100 + 0.5 (for the rounding).

def char_percentage(s: str, char: str) -> int:
    return floor(s.count(char) / len(s) * 100 + 0.5)
Enter fullscreen mode Exit fullscreen mode

The Perl solution is a bit more involved, as I don't believe there is a way to count the number of characters in a string. For this solution, I loop through each character and increase the occurrences value if is char.

my $occurrences = 0;
for my $pos ( 0 .. length($str) - 1 ) {
    if ( substr( $str, $pos, 1 ) eq $char ) {
        $occurrences++;
    }
}

say int( $occurrences / length($str) * 100 + 0.5 );
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py perl e
25

$ ./ch-1.py java a
50

$ ./ch-1.py python m
0

$ ./ch-1.py ada a
67

$ ./ch-1.py ballerina l
22

$ ./ch-1.py analitik k
13
Enter fullscreen mode Exit fullscreen mode

Task 2: B After A

Task

You are given a string, $str.

Write a script to return true if there is at least one b, and no a appears after the first b.

My solution

There are two likely ways to perform this task. One would be to take the position of last a (or -1 if there is no a) and check this is less than the position of the first b.

The second option is to use regular expressions. This is the approach that I took. The regexp I used is ^[^b]*b[^a]*$. This matches zero or characters other than b, a b and then makes sure there are no as after that.

Examples

$ ./ch-2.py aabb
True

$ ./ch-2.py abab
False

$ ./ch-2.py aaa
False

$ ./ch-2.py bbb
True
Enter fullscreen mode Exit fullscreen mode

Top comments (0)