Stars and bars counts the ways to share identical items among different people. Your program gives the count when children may get nothing and when each child must get at least one sweet.
What to build
A program that counts the ways to give out k identical sweets to n different children.
Requirements
- Read n and k on one line.
- Print
any:and the number of ways when any child may get no sweet. - Print
at least one each:and the number of ways when every child gets at least one sweet (0 if there is none).
Input
One line with n and k.
Output
Two lines.
Constraints
1 ≤ n ≤ 30; 0 ≤ k ≤ 60.
Example
Input:
3 6
Output:
any: 28
at least one each: 10
Why it works
Write the k sweets as stars and separate the children with n − 1 bars: a row of k + n − 1 symbols, of which we choose the positions of the k stars. When every child must get one, give one to each first and share the remaining k − n sweets freely, which gives C(k − 1, n − 1).
Examples
3 6
any: 28 at least one each: 10
2 5
any: 6 at least one each: 4
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Giving k identical sweets to n children with no limit is C(n + k - 1, k).
Hint 2
If every child needs at least one sweet, hand one to each first; then k - n sweets are left, so the count is C(k - 1, n - 1).
Hint 3
When k is smaller than n, nobody can get a sweet each: the answer is 0 (math.comb returns 0 for it when the lower number is bigger, but check k < n yourself).
Solution
Show one correct solution (try it yourself first)
from math import comb
n, k = map(int, input().split())
print("any:", comb(n + k - 1, k))
print("at least one each:", comb(k - 1, n - 1) if k >= n else 0)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step