Checking if string starts with list element

Kevin Digweed Kevin.Digweed at dial.pipex.com
Mon Aug 14 12:03:56 EDT 2000


Hi Simon.

Try something like:

import string

class lookup:
    def __init__(self, lst):
        self.data = {}
        for str in lst:
            key = str[:2]
            if not self.data.has_key(key):
                self.data[key] = []
            self.data[key].append(str)

    def find(self, str):
        key = str[:2]
        for item in self.data.get(key, ()):
            if str[:len(item)] == item:
                return item

romans = ['aqueduct', 'sanitation', 'roads', 'irrigation', 'medicine',
'education', 'wine', 'public baths', 'order']
us = 'wine, women and song.'

l = lookup(romans)
print l.find(us)

I chose a two-character key, but you could increase that up to the
length of the smallest of the 'special' words to get the best tradeoff
between number of keys in the dict vs length of the longest list under
those keys.

Cheers, Kev.

Simon Brunning wrote:
> 
> I have a list of strings:
> romans = ['aqueduct', 'sanitation', 'roads', 'irrigation', 'medicine',
> 'education', 'wine', 'public baths', 'order']
> 
> And I have a single string:
> us = 'wine, women and song.'
> 
> I want to know whether my sting *starts with* one of the strings in my list.
> The best that I can do is something like:
> 
> for roman in romans:
>     if string.find(us, roman) == 0:
>         # do stuff
>         break
> 
> The trouble is that in the code I'm writing, the list has a hundred or so
> elements, and it's running too slowly. Any suggestions?
> 
> Cheers,
> Simon Brunning
> TriSystems Ltd.
> sbrunning at trisystems.co.uk
> 
> -----------------------------------------------------------------------
> The information in this email is confidential and may be legally privileged.
> It is intended solely for the addressee. Access to this email by anyone else
> is unauthorised. If you are not the intended recipient, any disclosure,
> copying, distribution, or any action taken or omitted to be taken in
> reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
> accept liability for statements made which are clearly the senders own.



More information about the Python-list mailing list