DEV Community

SalahElhossiny
SalahElhossiny

Posted on

1

Most Common Word

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.


import re

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        #List words in paragraph, replacing punctuation with ' ' and all lower case
        paragraph = re.subn("[.,!?;']", ' ', paragraph.lower())[0].split(' ')

        #Remove any '' or words in banned from paragraph list
        paragraph = list(filter(lambda x: x not in banned + [''], paragraph))

        #Return most common word in filtered list
        return Counter(paragraph).most_common(1)[0][0]




Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay