Punnett Square Function: Matching Items in Lists

2020-07-29 17:48发布

问题:

I want to find all the possible gametes of a specific cross.

For example: 'AABB' x 'aabb' would be split into ['AA', 'BB'] and ['aa', 'bb']. I have that part done. After this, it should return: [['Aa', 'Aa', 'Aa', 'Aa'], ['Bb', 'Bb', 'Bb', 'Bb']] (for every allele in parent 'A', it matches with an allele in parent 'B'; this is a simplified Punnett Square).

This is what I have so far:

def punnett(a, b):
    n = int(len(a)/2)
    x = int(float(len(a)) / n)
    partsA, partsB, gametes = [a[i * x : i * x + x] for i in range(n)], [b[i * x : i * x + x] for i in range(n)], []
    for y in range(1, n):
        g = []
        for index in range(0, n/2 + y):
            for i in partsA[index]:
                for j in partsB[index]:
                    g.append(i+j)
        gametes.append(g)
    return gametes

It doesn't result in what I expected it would, though:

>>> punnett('AaBb', 'AaBb')
[['AA', 'Aa', 'aA', 'aa', 'BB', 'Bb', 'bB', 'bb']]

Also, a trihybrid cross does not give the results I expected, either:

>>> punnett('AaBbCc', 'AaBbCc')
[['AA', 'Aa', 'aA', 'aa', 'BB', 'Bb', 'bB', 'bb'], ['AA', 'Aa', 'aA', 'aa', 'BB', 'Bb', 'bB', 'bb', 'CC', 'Cc', 'cC', 'cc']]

If I could get input on what I'm doing wrong and how I could improve it, that would be great. Thanks!

回答1:

OK, I just read some materials on what you might want to achieve, and here is the changes

>>> from itertools import product, izip

If I understand correctly, an allele is consecutive characters ignoring case. In case of "AaBb" its ['Aa', and 'Bb']

>>> def allele(e):
    return [list(v) for _, v in groupby(e, key = str.lower)]

A Cross is defined as all possible crossover of the allele between the material and the parent

Followed by selection of the new genome from the crossover

>>> def punnett(a, b):
    return [''.join(e)
        for e in product(*([''.join(e) for e in product(*e)]
                    for e in izip(allele(a), allele(b))))]

>>> punnett('AaBbCc', 'AaBbCc')
['AABBCC', 'AABBCc', 'AABBcC', 'AABBcc', 'AABbCC', 'AABbCc', 'AABbcC', 'AABbcc', 'AAbBCC', 'AAbBCc', 'AAbBcC', 'AAbBcc', 'AAbbCC', 'AAbbCc', 'AAbbcC', 'AAbbcc', 'AaBBCC', 'AaBBCc', 'AaBBcC', 'AaBBcc', 'AaBbCC', 'AaBbCc', 'AaBbcC', 'AaBbcc', 'AabBCC', 'AabBCc', 'AabBcC', 'AabBcc', 'AabbCC', 'AabbCc', 'AabbcC', 'Aabbcc', 'aABBCC', 'aABBCc', 'aABBcC', 'aABBcc', 'aABbCC', 'aABbCc', 'aABbcC', 'aABbcc', 'aAbBCC', 'aAbBCc', 'aAbBcC', 'aAbBcc', 'aAbbCC', 'aAbbCc', 'aAbbcC', 'aAbbcc', 'aaBBCC', 'aaBBCc', 'aaBBcC', 'aaBBcc', 'aaBbCC', 'aaBbCc', 'aaBbcC', 'aaBbcc', 'aabBCC', 'aabBCc', 'aabBcC', 'aabBcc', 'aabbCC', 'aabbCc', 'aabbcC', 'aabbcc']
>>> punnett('AaBb', 'AaBb')
['AABB', 'AABb', 'AAbB', 'AAbb', 'AaBB', 'AaBb', 'AabB', 'Aabb', 'aABB', 'aABb', 'aAbB', 'aAbb', 'aaBB', 'aaBb', 'aabB', 'aabb']
>>>