Great post!
I had heard about the `groupby' function, but never about `clusterby' (which seems much more useful). You r first solution that you posted look pretty much how I would had done it. Although, I have to admit that Tom Moertel's solution is quite elegant.
Anyway, I improved slightly your translation of Moertel's solution. I think you will appreciate the few tweaks I did:
<pre><code>from collections import defaultdict
def sort(x):
return "".join(sorted(x))
def clusterby(iterable, key):
d = defaultdict(list)
for x in iterable:
d[key(x)].append(x)
return d.values()
c = clusterby([x+y for x in states for y in states], sort)
print max(c, key=len)</code></pre>
P.S.: Your anti-spam challenge is ambiguous.
Alexandre Vassalotti - 2007-12-14 23:13:28
Great post! I had heard about the `groupby' function, but never about `clusterby' (which seems much more useful). You r first solution that you posted look pretty much how I would had done it. Although, I have to admit that Tom Moertel's solution is quite elegant. Anyway, I improved slightly your translation of Moertel's solution. I think you will appreciate the few tweaks I did: <pre><code>from collections import defaultdict def sort(x): return "".join(sorted(x)) def clusterby(iterable, key): d = defaultdict(list) for x in iterable: d[key(x)].append(x) return d.values() c = clusterby([x+y for x in states for y in states], sort) print max(c, key=len)</code></pre> P.S.: Your anti-spam challenge is ambiguous.