Created
October 13, 2020 10:55
-
-
Save pandwoter/f83fbe44b51edb3ea3f7fc4fd6f71432 to your computer and use it in GitHub Desktop.
TOP K WORDS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def top_k_words(str, n) | |
return [] if n < 0 | |
str = str.downcase.scan(/[\w']+/) | |
occurances = Hash.new | |
str.each do |word| | |
if occurances[word] | |
occurances[word] += 1 | |
else | |
occurances[word] = 1 | |
end | |
end | |
p occurances | |
occurances.sort.sort_by { |word, occurence| [-occurence, -word] }[0..n-1].map {|x| x[0]}.join(" ") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment