[Tutor] Finding the shortest word in a list of words
Andreas Kostyrka
andreas at kostyrka.org
Wed Jan 21 18:39:57 CET 2009
Am Tue, 20 Jan 2009 09:33:40 -0600
schrieb "Paul McGuire" <ptmcg at austin.rr.com>:
No need for a defaultdict, all dicts have a setdefault method that
works fine for this assign an empty dict/list as starting point problem:
wordlendict = {}
for w in words:
wordlendict.setdefault(len(w), []).append(w)
try:
minlen, minlist = min(wordlendict.items())
except ValueError:
minlen = 0
minlist = []
Andreas
> from collections import defaultdict
> wordlendict = defaultdict(list)
> for w in words:
> wordlendict[len(w)].append(w)
> minlen = min(wordlendict.keys())
> minlist = wordlendict[minlen]
> print minlist
>
> prints:
> ['he', 'me']
>
> Now we are getting a more complete answer!
>
> A second approach uses the groupby method of the itertools module in
> the stdlib. groupby usually takes me several attempts to get
> everything right: the input must be sorted by the grouping feature,
> and then the results returned by groupby are in the form of an
> iterator that returns key-iterator tuples. I need to go through some
> mental gymnastics to unwind the data to get the group I'm really
> interested in. Here is a step-by-step code to use groupby:
>
> from itertools import groupby
> grpsbylen = groupby(sorted(words,key=len),len)
> mingrp = grpsbylen.next()
> minlen = mingrp[0]
> minlist = list(mingrp[1])
> print minlist
>
> The input list of words gets sorted, and then passed to groupby,
> which uses len as the grouping criteria (groupby is not inherently
> aware of how the input list was sorted, so len must be repeated).
> The first group tuple is pulled from the grpsbylen iterator using
> next(). The 0'th tuple element is the grouping value - in this case,
> it is the minimum length 2. The 1'th tuple element is the group
> itself, given as an iterator. Passing this to the list constructor
> gives us the list of all the 2-character words, which then gets
> printed: ['he', 'me']
>
> Again, 'me' no longer gets left out.
>
> Maybe this will get you some extra credit...
>
> -- Paul
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list