list problem

Gerard Flanagan grflanagan at yahoo.co.uk
Wed Jul 26 12:18:41 EDT 2006


placid wrote:
> Hi all,
>
> I have two lists that contain strings in the form string + number for
> example
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX5']
>
> the second list contains strings that are identical to the first list,
> so lets say the second list contains the following
>
> >>> list1 = [ ' XXX1', 'XXX2', 'XXX3', 'XXX6']
>
> and now what ive been trying to do is find the first string that is
> available,
> i.e a string that is in neither of the two lists so the following code
> should only print XXX4 then return.
>
> for i in xrange(1,10):
>     numpart = str(1) + str("%04i" %i)
>     str = "XXX" + numpart
>
>       for list1_elm in list1:
>           if list1_elm == str:
>                break
>           else:
>                for list2_elm in list2:
>                    if list2_elm == str:
>                       break
>                    else:
>                       print str
>                       return
>
> Cheer

I don't know how close the following is to what you want ( or how
efficient etc...).  If both lists are the same up to a certain point,
then the first function should do, if not, try the second function.

Gerard

from itertools import izip, dropwhile

def get_first_missing1( seq1, seq2 ):
    i = int( seq1[0][-1] )
    for x1, x2 in izip( seq1, seq2 ):
        if int(x1[-1]) != i and int(x2[-1]) != i:
            return x1[:-1] + str(i)
        i += 1
    return -1

def get_first_missing2( seq1, seq2 ):
    i = int( seq1[0][-1] )
    j = int( seq2[0][-1] )
    if j < i:
        seq1, seq2 = seq2, seq1
        i, j = j, i
    return get_first_missing1( list(dropwhile(lambda s: int(s[-1]) < j,
seq1)), seq2 )

L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5']
L2 = [ 'YYY1', 'YYY2', 'YYY3', 'YYY6']

print get_first_missing1(L1, L2)
print get_first_missing2(L1, L2)
'XXX4'
'XXX4'

L1 = [ 'XXX1', 'XXX2', 'XXX3', 'XXX5']
L2 = [ 'YYY2', 'YYY3', 'YYY5', 'YYY6']

print get_first_missing1(L1, L2)
print get_first_missing2(L1, L2)
'XXX4'
'XXX4'




More information about the Python-list mailing list