diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2024-02-11 16:57:38 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-02-11 16:57:38 +0000 |
| commit | c5a38cfc3a4ac9011ce409feb37558c58337b676 (patch) | |
| tree | 6ef501f14ad4ccb10ac9d95d9f9d7f2a0809e679 /challenge-255/sgreen/python/ch-2.py | |
| parent | 34fa48cf4b02c81fd6ed544498bde068aca981a2 (diff) | |
| parent | d4525399d41dd57f21bc11a67ceb63bdb16bc146 (diff) | |
| download | perlweeklychallenge-club-c5a38cfc3a4ac9011ce409feb37558c58337b676.tar.gz perlweeklychallenge-club-c5a38cfc3a4ac9011ce409feb37558c58337b676.tar.bz2 perlweeklychallenge-club-c5a38cfc3a4ac9011ce409feb37558c58337b676.zip | |
Merge pull request #9554 from simongreen-net/master
Simon's solution to challenge 255
Diffstat (limited to 'challenge-255/sgreen/python/ch-2.py')
| -rwxr-xr-x | challenge-255/sgreen/python/ch-2.py | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/challenge-255/sgreen/python/ch-2.py b/challenge-255/sgreen/python/ch-2.py new file mode 100755 index 0000000000..1a04788c22 --- /dev/null +++ b/challenge-255/sgreen/python/ch-2.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 + +import re +import sys + + +def most_frequent_word(p: str, b: str) -> str: + """Find the most frequent word that isn't banned + + Args: + p (str): The paragraph + b (str): The banned word + + Returns: + str: The most frequent word + """ + + # Calculate the frequency of all the words + freq = {} + for word in re.findall(r"\w+(?:'\w+)?", p.lower()): + freq[word] = freq.get(word, 0) + 1 + + # Remove the bad word (if it exists) + freq.pop(b, None) + + # Find the maximum occurrence of any word, and the word that has this + max_count = max(freq.values()) + words = [k for k in freq if freq[k] == max_count] + return words[0] + + +def main(): + result = most_frequent_word(sys.argv[1], sys.argv[2]) + print(result) + + +if __name__ == '__main__': + main() |
