【问题标题】:combinations of blocks with maximum height具有最大高度的块组合
【发布时间】:2014-06-09 04:20:13
【问题描述】:

考虑一个给定 N 个块的问题。它们必须彼此重叠排列(称为条形),并且必须放置许多这样的条形,因此跨条形的总块数等于 N。每种配置可以有尽可能多的位置变化组合。

例如,如果我有 6 个块,那么 (1,1,1,1,1,1) (1,2,2,1) (2,1,1,2) (2,2,1,1) ... (1,1,2,2)

每一列都是一个块。

我做了这样的事情:

def combinations_occur(N, limit = 3):
    l = []
    for i in xrange(1,N+1):
        tmp = []
        count = 0
        x = i if limit > i else limit
        while count != N:
            s = sum(tmp)
            extra = random.randint(1,x)
            while s + extra > N:
                extra -= 1
            tmp += [extra]
            #print sum(tmp),N
            if sum(tmp) == N:
                l += list(set(permutations(tmp,len(tmp))))
                break;
            else: count += 1
    return l

它使用 random 生成随机数 N 次,然后生成相同的排列以生成列表列表。产生类似的结果,例如 N = 6

(1, 1, 1, 1, 1, 1),
 (1, 1, 1, 1, 2),
 (1, 1, 1, 2, 1),
 (1, 1, 2, 1, 1),
 (1, 1, 2, 2),
 (1, 2, 1, 1, 1),
 (1, 2, 1, 2),
 (1, 2, 2, 1),
 (1, 2, 3),
 (1, 3, 2),
 (2, 1, 1, 1, 1),
 (2, 1, 1, 2),
 (2, 1, 2, 1),
 (2, 1, 3),
 (2, 2, 1, 1),
 (2, 2, 2),
 (2, 3, 1),
 (3, 1, 2),
 (3, 2, 1)

解不是最优的,解的顺序也不是最优的。 有人可以帮我解决这个问题,而且答案自然不能涵盖所有可能性,我想知道如何解决它。

【问题讨论】:

标签: python combinations


【解决方案1】:

Elegant Python code for Integer Partitioning 获取答案,并为每个结果使用itertools.permutations 进行排列。加入这些itertools.chain.from_iterable

from itertools import chain, permutations
chain.from_iterable(map(permutations, integer_partitions))

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 2018-02-06
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    相关资源
    最近更新 更多