python:intvectorrange
This is an old revision of the document!
# gives all possible integer vectors between two endpoints, inclusively. For example: # IntVectorRange([0,0,2], [1,1,3]) yields: # [0, 0, 2] # [1, 0, 2] # [0, 1, 2] # [1, 1, 2] # [0, 0, 3] # [1, 0, 3] # [0, 1, 3] # [1, 1, 3] # if only one argument is given to __init__, then the range goes from [0,0,...,0] to the vector given class IntVectorRange(object): def __init__(self,start,end=None): if end is None: end=start start=[0] * len(end) self.start=start self.end=end self.size = len(start) self.delta = [end[i]-start[i]+1 for i in xrange(self.size)] self.len = reduce(lambda x,y: x*y, self.delta, 1) def __getitem__(self,index): if index >= self.len: raise IndexError r = [0] * self.size for i in xrange(self.size): r[i] = index % self.delta[i] + self.start[i] index /= self.delta[i] return r def __len__(self): return self.len # provides a list with all possible subsets of the given list # (based on a binary IntVectorRange object) # # Example: AllCombinations(['alpha','beta','gamma']) yields: # [] # ['alpha'] # ['beta'] # ['alpha', 'beta'] # ['gamma'] # ['alpha', 'gamma'] # ['beta', 'gamma'] # ['alpha', 'beta', 'gamma'] class AllCombinations: def __init__(self,items): self.vector_range = IntVectorRange([1] * len(items)) self.items = items def __getitem__(self,index): v = self.vector_range[index] return [self.items[i] for i in xrange(len(v)) if v[i]] def __len__(self): return len(self.vector_range) # for academic purposes only, here's the same class based on inheritence instead of composition class AllCombinations2(IntVectorRange): def __init__(self,items): super(AllCombinations2,self).__init__([1] * len(items)) self.items = items def __getitem__(self,index): v = super(AllCombinations2,self).__getitem__(index) return [self.items[i] for i in xrange(len(v)) if v[i]]
python/intvectorrange.1288378375.txt.gz · Last modified: 2010/10/29 11:52 by tkbletsc