Distinguishable objects into distinguishable boxes
这与发布的这个问题非常相似。 我正在尝试获取此问题的python代码。 注意虽然它是相似的,但有一个关键的区别。即 存储桶可以为空,而其他存储桶包含所有项目。即便是这种情况也会被视为一个单独的案例。
例如:
考虑我有3个项目A,B,C和3个桶B1,B2,B3
下表将显示预期结果:
B1 B2 B3 (A,B,C) () () () (A,B,C) () () () (A,B,C) (A) (B) (C) (A) (C) (B) (B) (A) (C) (B) (C) (A) (C) (B) (A) (C) (A) (B) (A,B) (C) () (A,B) () (C) (B,C) (A) () (B,C) () (A) (A,C) (B) () (A,C) () (B) () (A,B) (C) (C) (A,B) () () (B,C) (A) (A) (B,C) () () (A,C) (B) (B) (A,C) () () (C) (A,B) (C) () (A,B) () (A) (B,C) (A) () (B,C) () (B) (A,C) (B) () (A,C) Length is 27.
>>def make_sets(items, num_of_baskets=3):
pass
>>make_sets(('A', 'B', 'C', 'D', 'E'), 3)
我期望函数的输出以元组列表的形式给出这些组合。我再说一遍,物品的数量是可变的,桶的数量也是可变的。
**请提供make_sets函数的python代码。
如果有人可以解释数学组合。我也非常感谢。我在这个问题上花了两天多的时间没有达成明确的解决方案。
答案 0 :(得分:0)
请注意,这对应于base-n数字(我希望你能美化输出)。该解决方案独立于n和k:
n = 5
k = 7
a = [0] * k
def to_base_n(x):
num = 0
while x is not 0:
num *= 10
num += x % n
x //= n
return num
for i in range(0, n ** k):
s = ('%0' + str(k) + 'd') % (to_base_n(i))
x = [list() for _ in range(n)]
for i in range(k):
x[int(s[i])].append(str(i))
print(x)
答案 1 :(得分:-1)
考虑逐个引入物品,每个人都必须选择一个可以降落的箱子。
从第一项开始,它有n
种可能的选择。现在第二个项目进来了,它还有n x n
个可能的框选项。由于项目和方框都是可区分的,我们不需要担心折扣排列(通常需要对无法区分的项目进行排序)。到目前为止,不同可能性的总数为n
。
带来第三项,它也有n x n x n
个选项,因此可能性的总数现在为n^k
。
您可能已经注意到,当您拥有k
项时,答案为n=3
。
在上述示例k=3
和3^3 = 27
中,我们有import itertools
def make_sets(items, num_of_boxes=3):
allpossible = []
for tup in itertools.product(range(num_of_boxes), repeat=len(items)):
boxes = [list() for _ in range(num_of_boxes)]
for item, box in zip(items, tup):
boxes[box].append(item)
allpossible.append(boxes)
return allpossible
for p in make_sets(('A', 'B', 'C')):
for box in p:
print str(box).ljust(20),
print
种放置项目的可能方式。
获取包含所有实际组合的列表的代码如下所示:
['A', 'B', 'C'] [] []
['A', 'B'] ['C'] []
['A', 'B'] [] ['C']
['A', 'C'] ['B'] []
['A'] ['B', 'C'] []
['A'] ['B'] ['C']
['A', 'C'] [] ['B']
['A'] ['C'] ['B']
['A'] [] ['B', 'C']
['B', 'C'] ['A'] []
['B'] ['A', 'C'] []
['B'] ['A'] ['C']
['C'] ['A', 'B'] []
[] ['A', 'B', 'C'] []
[] ['A', 'B'] ['C']
['C'] ['A'] ['B']
[] ['A', 'C'] ['B']
[] ['A'] ['B', 'C']
['B', 'C'] [] ['A']
['B'] ['C'] ['A']
['B'] [] ['A', 'C']
['C'] ['B'] ['A']
[] ['B', 'C'] ['A']
[] ['B'] ['A', 'C']
['C'] [] ['A', 'B']
[] ['C'] ['A', 'B']
[] [] ['A', 'B', 'C']
运行以上打印输出:
$fileArray= array("name1.pdf","name2.pdf","name3.pdf","name4.pdf");
$datadir = "save_path/";
$outputName = $datadir."merged.pdf";
$cmd = "gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$outputName ";
//Add each pdf file to the end of the command
foreach($fileArray as $file) {
$cmd .= $file." ";
}
$result = shell_exec($cmd);