I think that this does the same as your code, although it seems to me that this is not want you really want because the pairs (A,B) of subgroups that you return will not in general have the property that G=A x B. I have not played at all with groups in sage before so this may be far from optimal:
def direct_summands(G):
r"""
Return the direct summands of the abelian group ``G``.
EXAMPLES::
sage: direct_summands( CyclicPermutationGroup(4) )
[(Permutation Group with generators [()], Permutation Group with generators [(1,2,3,4)]),
(Permutation Group with generators [(1,3)(2,4)], Permutation Group with generators [(1,3)(2,4)])]
"""
if not (G in Groups and G.is_finite() and G.is_abelian() ):
raise ValueError, '%s must be a finite abelian group' % G
# will create a dictionary of the subgroups in G up to isomorphism indexed by size
subgroups_by_size={}
for H in G.subgroups(): # loop over *all* subgroups of G
h=H.cardinality()
if h in subgroups_by_size:
if not all(H.is_isomorphic(K) for K in subgroups[h]):
subgroups_by_size[h].append(H)
else:
subgroups_by_size[h]=[H]
# n is the number of divisors of |G|
g=G.cardinality()
divisors = [(d, g/d) for d in g.divisors() if 2*d<=g]
return [(A,B) for (d,e) in divisors if d in subgroups_by_size and e in subgroups_by_size
for A in subgroups_by_size[d] for B in subgroups_by_size[e] ]
Put this into a file, say, summands,py, and then type
sage: attach summands,py
inside sage.
As a general rule, you can find out what to do using tab-completion. For example, if you type
sage: G=CyclicPermutationGroup(4)
sage: G.<tab>
then you will get a list of the methods that apply to the group G.
Andrew