设置固定大小的分区

时间:2016-04-21 11:19:14

标签: python-3.x

我需要找到固定大小块的set分区。例如,设置S =(1,2,3,4,5,6,7),我想将其分区为(4,2,1)的块。答案是

([1,2,3,4][5,6][7])
([2,3,4,5][6,7][1])
 ([1,4,5,6][2,3][7])
 .....................
 .....................

任何人都知道如何在Python中轻松解决它。请提供一些线索

2 个答案:

答案 0 :(得分:4)

你必须以7 * 6 * 5 * 4 * 3 * 2 * 1的方式对你的桌子进行置换,然后将每张桌子分成几部分。

例如:

def permute(table):
    return [[],[],[],[],...]//table of permuted tables


def cut_into_parts(lengths_list, table):
    rlist = []
    for i in lengths_list[:-1]:
        rlist.append(table[:-len(table) + i])
        table = table[i:]
    rlist.append(table[:lengths_list[-1]])
    return rlist

我希望这很容易,也很有帮助。如果是

,请标记

答案 1 :(得分:2)

尝试以下功能:

from itertools import permutations

def take(l, partition):
  if len(partition) == 1:
    for p in permutations(l):
      yield (p,)
  else:
    for p in permutations(l,partition[0]):
      for t in take([x for x in l if x not in p], partition[1:]):
        yield (p,) + t

然后take([1,2,3,4,5,6,7],(4,2,1))应该是您正在寻找的。

编辑:不同的解决方案现在我更好地理解要求:

from itertools import permutations

def take(l, partition):
  offsets = [0]
  for x in partition:
    offsets.append(offsets[-1]+x)
  for p in permutations(l):
    yield frozenset([frozenset(p[offsets[i]:offsets[i+1]]) for i in range(len(offsets)-1)])


for x in frozenset(take([1,2,3,4,5],(3,1,1))):
  print([[z for z in y] for y in x])