![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements