Hi All
I was writing a bit of code to solve Euler Project #90, and came across the need to iterate through all combinations of a particular list. Any improvements would be most welcome, but I thought a class with an iterator would be appropriate.
Here's the class with a bit of code.
This code will print out:
['a','b','c']
['a','b','d']
['a','b','e']
['a','c','d']
['a','c','e']
['a','d','e']
['b','c','d']
['b','c','e']
['b','d','e']
['c','d','e']
It's helpful for Euler Project type things!
I was writing a bit of code to solve Euler Project #90, and came across the need to iterate through all combinations of a particular list. Any improvements would be most welcome, but I thought a class with an iterator would be appropriate.
Here's the class with a bit of code.
Code:
class myComb(object):
"""my interable combinatorial object"""
def __init__(self,elements,length):
if len(elements)>length:
self.length=length
self.elements=elements
self.noEls=len(elements)
def comb(self):
"""return the combination for the current index"""
c=[]
for i in self.index:
c.append(self.elements[i])
return c
def __iter__(self):
self.index=range(self.length)
self.index[self.length-1]+=-1
return self
def next(self):
if self.index==range(self.noEls-self.length,self.noEls):
raise StopIteration
i=self.length-1
while self.index[i]==self.noEls-self.length+i:
i+=-1
self.index[i]+=1
for j in range(i+1,self.length):
self.index[j]=self.index[j-1]+1
return self.comb()
C=myComb(["a","b","c","d","e"],3)
for i in C:
print i
['a','b','c']
['a','b','d']
['a','b','e']
['a','c','d']
['a','c','e']
['a','d','e']
['b','c','d']
['b','c','e']
['b','d','e']
['c','d','e']
It's helpful for Euler Project type things!
Comment