Rita Sue and Bob too

Peter Hansen peter at engcorp.com
Fri Aug 20 18:32:39 CEST 2004


M. Clift wrote:

> If I wasn't happy enough already with the examples/ideas you've all shown
> me, how about searching as previously, but where the middle name could be
> anything. i.e. 'Rita', 'anyname','Bob'

How about this? (may need more test cases, and then perhaps fixes):


class Anything:
     '''wildcard: matches anything'''
     pass


def sliceCompare(left, right):
     '''compare left and right, returning True if equal (allows wildcard)'''
     if len(left) != len(right):
         return False
     else:
         for l, r in zip(left, right):
             if Anything in [l, r]:
                 pass
             elif l != r:
                 return False
         else:
             return True


def sliceIndex(seq, sub, start=0):
     '''search starting at 'start' for sub in seq, return index of match 
or -1'''
     try:
         i = seq.index(sub[0], start)
         while i >= 0:
             if sliceCompare(seq[i:i+len(sub)], sub):
                 return i
             i = seq.index(sub[0], i+1)
     except ValueError:
         pass
     return -1



def test():
     case1 = ['Rita', 'Sue', 'Bob']
     alist = 'Rita Mary Jane Bob Sue Carl Hans Rita Bob Sue'.split()
     assert sliceIndex([], case1) == -1
     assert sliceIndex(alist, case1) == -1

     alist = 'Rita Mary Jane Bob Rita Carl Bob Hans Rita Sue Bob Sue 
Rita Sue Bob'.split()
     assert sliceIndex(alist, case1) == 8
     assert sliceIndex(alist, case1, 9) == 12
     assert sliceIndex(alist, case1, 13) == -1

     case2 = ['Rita', Anything, 'Bob']
     assert sliceIndex(alist, case2) == 4
     assert sliceIndex(alist, case2, 5) == 8
     assert sliceIndex(alist, case2, 9) == 12


if __name__ == '__main__':
     test()



More information about the Python-list mailing list