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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With