Combination iteration

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    Combination iteration

    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.

    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
    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!
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    So I feel like a bit of a clown, but the exact same thing can be done with the built-in module itertools.

    It has permutations, combinations and product:
    Here are the docs

    But basic usage is:
    Code:
    In [17]: P=itertools.permutations([1,2,3])
    
    In [18]: for p in P:
       ....:     print p
       ....:     
       ....:     
    (1, 2, 3)
    (1, 3, 2)
    (2, 1, 3)
    (2, 3, 1)
    (3, 1, 2)
    (3, 2, 1)

    Comment

    Working...