Python 中的笛卡尔积
Cartesian product in Python
我正在尝试绘制 "stars-and-bars" 问题的散点图。在 X-axis 我有 "number of children to distribute candies to",在 Y-axis "number of candies to distribute"。在 Z-axis 我有“多种分发方式。
我使用嵌套 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')
问题是,当我检查我的数据集时,我看到像 (1,5,1)、(1,6,1) 等条目,这意味着有 1 种方法可以在 5 children,或将 1 颗糖果分给 6 children 的 1 种方式。但事实并非如此,有 5 种方法可以将 1 颗糖果分给 5 children 和 6 种方式可以将 1 颗糖果分给 6 children。我肯定在这里做错了一些事情,但我想不通。
您的 mylist
计算正在寻找所有方法将 i-1
糖果分配给 j
children,而不是 i
糖果。在 5 children,或 6 children,或任意数量的 children 之间,只有一种方法可以分配 0 个糖果:没有人得到任何东西。
我正在尝试绘制 "stars-and-bars" 问题的散点图。在 X-axis 我有 "number of children to distribute candies to",在 Y-axis "number of candies to distribute"。在 Z-axis 我有“多种分发方式。
我使用嵌套 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')
问题是,当我检查我的数据集时,我看到像 (1,5,1)、(1,6,1) 等条目,这意味着有 1 种方法可以在 5 children,或将 1 颗糖果分给 6 children 的 1 种方式。但事实并非如此,有 5 种方法可以将 1 颗糖果分给 5 children 和 6 种方式可以将 1 颗糖果分给 6 children。我肯定在这里做错了一些事情,但我想不通。
您的 mylist
计算正在寻找所有方法将 i-1
糖果分配给 j
children,而不是 i
糖果。在 5 children,或 6 children,或任意数量的 children 之间,只有一种方法可以分配 0 个糖果:没有人得到任何东西。