简体   繁体   English

Python中的笛卡尔积

[英]Cartesian product in Python

I am trying to do a scatter plot of "stars-and-bars" problem. 我正在尝试绘制“星条”问题的散点图。 On X-axis I have "number of children to distribute candies to", on Y-axis "number of candies to distribute". 在X轴上,我有“要分发糖果的孩子数”,在Y轴上有“要分发糖果的数目”。 On Z-axis I have "number of ways to distribute. 在Z轴上,我有“多种分配方式。

I use nested for loops to generate dataset for plotting: 我使用嵌套的for循环来生成用于绘制的数据集:

import itertools as it
import math
import numpy as np
import matplotlib as mlp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x_coordinate = np.arange(16)
y_coordinate = np.arange(16)
dataset = []
for i in range(10):
    for j in range(10):
    mylist = [item for item in it.product(range(i), repeat = j) if sum(item) == (i-1)]
    z_value = len(mylist) 
    x_value = i
    y_value = j
    dataset.append((x_value, y_value, z_value))  
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
x = [item[0] for item in dataset]
y = [item[1] for item in dataset]
z = [item[2] for item in dataset]
ax.scatter(x,y,z,c='r')
ax.set_xlabel('Candies')
ax.set_ylabel('Children')
ax.set_zlabel('Search space')

The problem is that when I check my dataset, I see entries like (1,5,1), (1,6,1) etc. that imply that there is 1 way to distribute 1 candy among 5 children, or 1 way to distribute 1 candy among 6 children. 问题是当我检查数据集时,我看到诸如(1,5,1),(1,6,1)等条目,这暗示着有一种方法可以在5个孩子中分配1个糖果,或者有1种方法可以在6个孩子中分发1个糖果。 But this is not true, there are 5 ways to distribute 1 candy among 5 children and 6 ways to distribute 1 candy among 6 children. 但这是不正确的,有5种方法在5个孩子中分配1个糖果,还有6种方法在6个孩子中分配1个糖果。 I am certainly doing something terribly wrong here, but i can't figure it out. 我当然在这里做错了非常严重的事情,但是我无法弄清楚。

Your mylist computation is finding all ways to distribute i-1 candies to j children, not i candies. 您的mylist计算方法正在寻找将i-1糖果分发给j孩子(而不是i糖果)的所有方法。 There is exactly 1 way to distribute 0 candies between 5 children, or 6 children, or any number of children: no one gets anything. 在5个孩子,6个孩子或任意数量的孩子之间分配0个糖果的方法是完全正确的一种:没有人得到任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM