This is part of my program for generating punnet squares. It should separate a “genome” of the form [[‘A’,’a’],[‘b’,’b’],[‘C’,C’]…] into possible gametes:
def gene_erator2(gen):
gam = [[], []]
q = 0
for x in gen:
q = q + 1
if q > 1:
gamgam = gam[:]
for z in gam:
gamgam.append(z)
gam = gamgam[:]
for y in range(len(gam)):
if y < len(gam)/2:
gam[y].append(x[0])
else:
gam[y].append(x[1])
return gam
When I execute
gene_erator2([['A','a'], ['B','b'], ['X','Y']])
I get
[['A', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['a', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['A', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['a', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['A', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['a', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['A', 'B', 'b', 'X', 'X', 'Y', 'Y'], ['a', 'B', 'b', 'X', 'X', 'Y', 'Y']]
instead of the expected
[['A', 'B', 'X'], ['a', 'B', 'X'], ['A', 'b', 'X'], ['a', 'b', 'X], ['A', 'B', 'Y'], ['a', 'B', 'Y'], ['A', 'b', 'Y'], ['a', 'b', 'Y']]
….What? I mean, just What?
EDIT:
I now know the function that does what I want thanks to Shang, but I still want to know what was wrong with my code….
There’s a function that does what you want in the standard library.
This returns an iterator, which lets you iterate over all the combinations.