Tuesday, 15 June 2010

Comparing 3 lists in Python -



Comparing 3 lists in Python -

the next code compares 3 lists, motherlist fatherlist , sonlist, checking see if every value in sonlist represented in either motherlist or fatherlist once.

def comparelist(motherlist, fatherlist, sonlist): count = 0 x in sonlist: if x in motherlist , x in fatherlist: count = 2 elif x in motherlist or x in fatherlist: count += 1 if count >= 2: ans = "mendelion" else: ans = "non-medelian" print"{0} {1} \t {2} \t {3}".format(motherlist, fatherlist, sonlist, ans)

outputting:

['0'] ['0'] ['4'] non-mendelion ['2', '6'] ['0'] ['0', '2'] mendelion ['1'] ['0'] ['1'] non-medelian ['-1', '2'] ['-4', '-1'] ['-4', '2'] mendelion

is there neater way accomplish this? perhaps through recursive or non recursive means

use sets, friend.

in [1]: {0, 1, 2} & {1, 2, 3} & {2, 3, 4} out[1]: set([2])

so code like:

if set(motherlist) & set(fatherlist) & set(sonlist): ans = "mendelion" else: ans = "non-medelian"

first of, looks really-really developer, secondly not expensive, depends on info sizes.

sets special type in python, gives ability find intersections(which values in both sets) , differences, soo handy utilize in many-many situations.

python list compare

No comments:

Post a Comment