DEV Community

Simon Green
Simon Green

Posted on

The most odd thing

Weekly Challenge 255

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: Odd Character

Task

You are given two strings, $s and $t. The string $t is generated using the shuffled characters of the string $s with an additional character.

Write a script to find the additional character in the string $t.

My solution

I have created a function frequency_count that counts the frequency of each character in a string.

def frequency_count(s: str) -> dict:
    freq = {}

    for c in s:
        freq[c] = freq.get(c, 0) + 1

    return freq
Enter fullscreen mode Exit fullscreen mode

I then calculate the frequency for each letter in both strings. Finally I iterate through each letter in the second string, and return the character where the frequency is higher in the second string than the first.

def odd_character(s: str, t: str) -> str:
    first_freq = frequency_count(s)
    second_freq = frequency_count(t)

    for c in second_freq:
        if second_freq[c] > first_freq.get(c, 0):
            return c
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-1.py Perl Preel
e

$ ./ch-1.py Weekly Weeakly
a

$ ./ch-1.py Box Boxy
y
Enter fullscreen mode Exit fullscreen mode

Task 2: Most Frequent Word

Task

You are given a paragraph $p and a banned word $w.

Write a script to return the most frequent word that is not banned.

My solution

For this challenge, I need to determine what is a word. I use the regular expression \w+(?:'\w+)? which will capture words that have an apostrophe in it, like "isn't" while excluding where it is used as a quote start/end. I also convert the string to lower case to catch cases where the word might be in a different case.

With that in mind, I go through the string and count the frequency of all the words in a dict called freq.

freq = {}
for word in re.findall(r"\w+(?:'\w+)?", p.lower()):
    freq[word] = freq.get(word, 0) + 1
Enter fullscreen mode Exit fullscreen mode

I then remove the bad word (if it exists)

freq.pop(b, None)
Enter fullscreen mode Exit fullscreen mode

Finally, I find the maximum frequency, and the word that has that frequency.

max_count = max(freq.values())
words = [k for k in freq if freq[k] == max_count]
return words[0]
Enter fullscreen mode Exit fullscreen mode

Examples

$ ./ch-2.py "Joe hit a ball, the hit ball flew far after it was hit." hit
ball

$ ./ch-2.py "Perl and Raku belong to the same family. Perl is the most popular language in the weekly challenge." the
perl
Enter fullscreen mode Exit fullscreen mode

Top comments (0)