Rita Sue and Bob too

Peter Otten __peter__ at web.de
Sat Aug 21 12:48:57 CEST 2004


Peter Hansen wrote:

> 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):

A properly crafted test suite invites refactoring :-)

class Anything:
     '''wildcard: matches anything'''
     def __eq__(self, other):
        return True
Anything = Anything() # bad style, I know

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 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