[Tutor] printing answers

Karl Pflästerer sigurd at 12move.de
Thu Feb 5 18:55:29 EST 2004


On  5 Feb 2004, Rich Krauter <- rmkrauter at yahoo.com wrote:

> I think you're making it much harder than it needs to
> be by using regexes and nested loops. 
> Notice I use answers as a dict, not a list. Dicts are
> nice when you want to get rid of repeats.

ACK.

[Code]

But you lose information the way you wrote the code.  In the example of
the OP the case didn't matter but didn't get lost.

Furthermore try / except without an explicit error condition is
dangerous.  You also catch errors you perhaps didn't think about.

So the code should be written a bit different IMO.

def find_match(lst):
    answers = {}
    res = []
    for s in lst:
        sl = s.lower()
        answers.setdefault(sl,[]).append(s)
    for key, val in answers.items():
        if len(val) > 1:
            res.extend(val)
    return res

The lowered string is used as key and a list with the original strings
gets used as value.  Each value list which has a length > 1 gets pushed
into the result list which is finally returned.

The setdefault method of dictionaries is very handy here.  If called
with an existing key it returns the appendant value or the second
argument (which is the empty list here); the append method then adds the
string to the list.


   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list