Skip to content

Instantly share code, notes, and snippets.

@alexandre
Last active August 29, 2015 14:08
Show Gist options
  • Save alexandre/f03f98a8e5ba9fddd0be to your computer and use it in GitHub Desktop.
Save alexandre/f03f98a8e5ba9fddd0be to your computer and use it in GitHub Desktop.
word counter
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)}
@NicolasFrancaX
Copy link

Javascript:

function word_counter(words) {
  var counter = {};

  words.split(' ').map(function(word) {
    !counter[word] ? counter[word] = 1 : counter[word] += 1;
  });

  return counter;
}

var frase = 'vaca batata galinha batata coxinha macaco batata vaca batata';

word_counter(frase); 
// => Object {vaca: 2, batata: 4, galinha: 1, coxinha: 1, macaco: 1}

@Eldius
Copy link

Eldius commented Nov 10, 2014

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"))
}

@alexandre
Copy link
Author

Outra versão em python....:

def word_counter(string):
    return {x: string.count(x) for x in string.split()}

@alexandre
Copy link
Author

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