
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to count the number of ways to distribute n number of candies in k number of bags in Python
Suppose, there are n number of candies and k bags in which the candies have to put into. We have to find out the number of possible ways the candies can be distributed so that each bag contains at least one candy. Every candy in this scenario is unique, so we have to count all the possible ways the candies can be distributed in the bags.
So, if the input is like n = 3, k = 2, then the output will be 3.
The candies can be put in this manner −
(1, 2), (3) (1) , (2, 3) (2), (1, 3)
To solve this, we will follow these steps −
dp := a matrix of size n x n initialized with value 1
for c in range 2 to n, do
for b in range 1 to minimum of (c, k), do
dp[c, b] := dp[c-1, b-1] + dp[c-1, b] * (b+1)
return dp[n-1, k-1]
Example
Let us see the following implementation to get better understanding −
def solve(n, k): dp = [[1] * n for _ in range(n)] for c in range(2, n): for b in range(1,min(c,k)): dp[c][b] = dp[c-1][b-1] + dp[c-1][b] * (b+1) return dp[n-1][k-1] print(solve(3, 2))
Input
3, 2
Output
3
- Related Articles
- Program to count number of ways we can distribute coins to workers in Python
- Program to count number of ways we can throw n dices in Python
- Program to count number of ways to win at most k consecutive games in Python
- Write a program in Python to count the number of digits in a given number N
- Program to count number of stepping numbers of n digits in python
- Program to count number of paths whose sum is k in python
- Program to count number of BST with n nodes in Python
- Count number of ways to divide a number in parts in C++
- Count number of ways to partition a set into k subsets in C++
- Distribute Candies to People in Python
- Program to count number of sublists with exactly k unique elements in Python
- Number of Ways to Paint N × 3 Grid in C++ program
- Program to count the number of consistent strings in Python
- Python program to count the number of spaces in string
- Program to count number of palindromic substrings in Python

Advertisements