Skip to content Skip to sidebar Skip to footer

Yield Sub Combinations With Limit

I'm working with python 3. The function I'm working with is as follows: def sub_combinations(segment): if len(segment) == 1: yield (segment,) else: for j in sub_combin

Solution 1:

I think the following change results in the output you are looking for:

defsub_combinations(segment, max_offset=None):
   data = tuple([e] for e in segment)
   def_sub_combinations(segment):
      iflen(segment) == 1:
         yield (segment,)
      else:
         for j in _sub_combinations(segment[1:]):
            yield ((segment[0],),)+j
            for k inrange(len(j)):
               if max_offset and data.index(j[k][0]) - data.index(segment[0]) > max_offset:
                  breakyield (((segment[0],)+j[k]),) + (j[:k]) +(j[k+1:])
   for combination in _sub_combinations(data):
      yieldtuple(tuple(e[0] for e in t) for t in combination)

The idea here is that you break out of the k loop instead of yielding a tuple that would have an offset larger than max_offset.

Post a Comment for "Yield Sub Combinations With Limit"