Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Codewars 4 kyu "Most frequently used words in a text" with Python

$
0
0

Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences.

Assumptions:A word is a string of letters (A to Z) optionally containing one or more apostrophes (') in ASCII.Apostrophes can appear at the start, middle or end of a word ('abc, abc', 'abc', ab'c are all valid)Any other characters (e.g. #, , / , . ...) are not part of a word and should be treated as whitespace.Matches should be case-insensitive, and the words in the result should be lowercased.Ties may be broken arbitrarily.If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words.

def top_3_words(text):    res = {}    textf = ''.join([char.lower() for char in text if char.isalpha() or char == '' or char == "'"]).split('') # Create list with the allowed chars in lower case, join it and split it    for char in textf:        if char.replace("'", '').isalpha():            if char in res:                res[char] += 1            else:                res[char] = 1    return [i for i, j in sorted(res.items(), key=lambda res: res[1], reverse=True)][:3]

The program passes the fixed codewars tests, as far as I know the code is correct, but, there's only a few of the random tests are returning correct, and I don't think I can see the random tests that are being apllied. Does someone understand why this is not working? or is the problem on codewars?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>