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)} |
using System;
using System.Linq;
using System.Collections.Generic;
namespace WordCount
{
class Program
{
public static void Main(string[] args)
{
String phrase = "vaca batata galinha batata coxinha macaco batata vaca batata";
List<String> words = phrase.Split ( ' ' ).ToList ();
foreach ( var group in words.GroupBy ( p => p ) )
Console.WriteLine ( "{0} - {1}", group.Key, group.Count ());
}
}
}
Groovy:
def wordCount(text) {
def map = [:]
def words = text.split(" ")
words.each() { word ->
map.putAt(word, map.get(word, 0) + 1)
}
map
}
def text = "vaca batata galinha batata coxinha macaco batata vaca batata"
def map = wordCount(text)
map.each { key, value -> println """${key}: ${value} """ }
Shell script, using arguments:
#!/bin/sh
echo $@ | tr ' ' '\n' | sort | uniq -c
e.g.:
./wordcounter.sh vaca batata galinha batata coxinha macaco batata vaca batata
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}
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
Lisp L-99:
(GALINHA COXINHA MACACO (2 VACA) (4 BATATA))