user9695260
user9695260

Reputation: 367

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". On Z-axis I have "number of ways to distribute.

I use nested for loops to generate dataset for plotting:

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. 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. I am certainly doing something terribly wrong here, but i can't figure it out.

Upvotes: 0

Views: 208

Answers (1)

user2357112
user2357112

Reputation: 280837

Your mylist computation is finding all ways to distribute i-1 candies to j children, not i candies. There is exactly 1 way to distribute 0 candies between 5 children, or 6 children, or any number of children: no one gets anything.

Upvotes: 1

Related Questions