View Problem

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
DiskEdit
python
c = defaultdict(list)
for k in ["one", "two", "four", "three", "five"]:
c[len(k)].append(k)
DiskEdit
python
from itertools import groupby
lst = ["one", "two", "four", "three", "five"]
c = dict((k, list(g)) for k,g in
groupby(sorted(lst, key=lambda x: len(x)), key=lambda x: len(x)))
print(c)
DiskEdit
csharp .NET 3.5
using System.Collections.Generic;
using System.Linq;
public class ListCategorizer {
public static void Main() {
var list = new List<string>() { "one", "two", "three", "four", "five" };
var categories = list.GroupBy(el => el.Length)
.ToDictionary( g => g.Key, // key
g => g.ToList() ); // value
}
}
ExpandDiskEdit
java
SortedMap<Integer, List<String> > map = new TreeMap<Integer, List<String> >(); int key; List<String> vlist;

for (String item : list)
{
key = item.length(); vlist = map.containsKey(key) ? map.get(key) : new ArrayList<String>();
vlist.add(item); map.put(key, vlist);
}
ExpandDiskEdit
java org.apache.commons
MultiValueMap map = new MultiValueMap();
for (Object item : list) map.put(((String) item).length(), item);
ExpandDiskEdit
erlang
% Imperative Solution
CatList = categorise(List),
ExpandDiskEdit
erlang
% Functional (1) Solution
CatList = categorise(List),
ExpandDiskEdit
cpp C++/CLI .NET 2.0
for each(String^ entry in input)
{
key = entry->Length;
if (!hash->ContainsKey(key)) hash[key] = gcnew ArrayList;
safe_cast<ArrayList^>(hash[key])->Add(entry);
}

Submit a new solution for python, csharp, java, erlang ...
There are 17 other solutions in additional languages (clojure, fantom, fsharp, groovy ...)