Last active
August 29, 2015 14:08
-
-
Save alexandre/f03f98a8e5ba9fddd0be to your computer and use it in GitHub Desktop.
word counter
This file contains hidden or 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
from itertools import groupby | |
def word_counter(*words): | |
'''Write a Python program that inputs a list of words, separated by white- | |
space, and outputs how many times each word appears in the list. | |
''' | |
return {word: len(list(word_group)) for word, word_group in | |
groupby(sorted(words), key=lambda x: x)} |
Scala
object Test extends App{
def count(text: String): Map[String, Int] = {
def count(words: Array[String]): Map[String, Int] = {
if(words.size == 1) {
return Map(words.head -> 1)
} else {
val map = count(words.tail)
return map + (words.head -> (map.getOrElse(words.head, 0) + 1))
}
}
return count(text.split(" "))
}
println(count("vaca batata galinha batata coxinha macaco batata vaca batata"))
}
Outra versão em python....:
def word_counter(string):
return {x: string.count(x) for x in string.split()}
Outra versão ainda mais simples:
import collections
def word_counter(*string):
return dict(collections.Counter(string).items())
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Javascript: