C
Christian Meesters
Hi,
I'd like to hack a function which returns all possible permutations as lists
(or tuples) of two from a given list. So far, I came up with this solution,
but it turned out to be too slow for the given problem, because the list
passed ("atomlist") can be some 1e5 items long:
def permute(atomlist, size = 2):
"""
returns a list of atoms grouped by two
"""
if not size or not atomlist:
return [atomlist[:0]]
else:
result = list()
for i in xrange(len(atomlist)):
pick = atomlist[i:i+1] # sequence slice
remainder = atomlist[:i] + atomlist[i+1:] # keep [:i] part
for x in __permute(remainder, size = size - 1):
result.append(pick + x)
return result
Does anybody know a solution which consumes less memory and is possibly
faster, perhaps using generator expressions? All my attempts so far failed.
Any help appreciated!
TIA
Christian
I'd like to hack a function which returns all possible permutations as lists
(or tuples) of two from a given list. So far, I came up with this solution,
but it turned out to be too slow for the given problem, because the list
passed ("atomlist") can be some 1e5 items long:
def permute(atomlist, size = 2):
"""
returns a list of atoms grouped by two
"""
if not size or not atomlist:
return [atomlist[:0]]
else:
result = list()
for i in xrange(len(atomlist)):
pick = atomlist[i:i+1] # sequence slice
remainder = atomlist[:i] + atomlist[i+1:] # keep [:i] part
for x in __permute(remainder, size = size - 1):
result.append(pick + x)
return result
Does anybody know a solution which consumes less memory and is possibly
faster, perhaps using generator expressions? All my attempts so far failed.
Any help appreciated!
TIA
Christian