Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 3 lists in Python

The following code compares three lists, motherList fatherlist and sonList, checking to see if every value in sonList is represented in either motherList or fatherList once.

def compareList(motherList, fatherList, sonList):
    count = 0
    for x in sonList:
            if x in motherList and 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 a neater way to accomplish this? Perhaps through recursive or non recursive means

like image 942
Sean Avatar asked Dec 26 '22 07:12

Sean


2 Answers

Use sets, my friend.

In [1]: {0, 1, 2} & {1, 2, 3} & {2, 3, 4}
Out[1]: set([2])

So your code will look like:

if set(motherList) & set(fatherlist) & set(sonList):
    ans = "Mendelion"
else:
    ans = "Non-Medelian"

First of, it looks really-really good for any developer, secondly it is not so expensive, but depends on data sizes.

Sets is a special type in python, which gives you ability to find intersections(which values are in both sets) and differences, which is soo handy to use in many-many situations.

like image 132
dt0xff Avatar answered Dec 31 '22 12:12

dt0xff


What you're looking for is a set operation. Python sets already enforce the condition that all items are unique, and you can do things like this:

child_set <= (mother_set ^ father_set)

which creates a set of the symmetric difference between the mother and father sets (all items that are in one or the other but not both), and then tests that every item in child set is in that set.

Further reading: https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset

like image 36
whereswalden Avatar answered Dec 31 '22 13:12

whereswalden