From an m-element set to an n-element set there are many functions, and counting the one-to-one and onto ones needs the counting tools of the course. Your program prints all four counts.
What to build
A program that counts all, one-to-one, onto and bijective functions from an m-set to an n-set.
Requirements
- Read m and n on one line: the size of the domain and of the codomain.
- Print
all functions:and n to the power m. - Print
one-to-one:and the number of injective functions. - Print
onto:and the number of surjective functions. - Print
bijections:and the number of bijective functions.
Input
One line with m and n.
Output
Four lines.
Constraints
1 ≤ m, n ≤ 12.
Example
Input:
3 2
Output:
all functions: 8
one-to-one: 0
onto: 6
bijections: 0
Why it works
Each of the m inputs picks one of n outputs, giving n to the power m functions. Injective choices use up one output each time, giving n(n−1)...(n−m+1). Surjective functions are all functions minus those that miss at least one output, counted with inclusion-exclusion over the outputs that are missed. A bijection needs m = n and is then a rearrangement, so m! of them.
Examples
3 2
all functions: 8 one-to-one: 0 onto: 6 bijections: 0
3 3
all functions: 27 one-to-one: 6 onto: 6 bijections: 6
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The number of all functions is n**m, and of one-to-one functions is math.perm(n, m) (zero when m > n).
Hint 2
Onto functions by inclusion-exclusion: the sum over k from 0 to n of (-1)**k * comb(n, k) * (n - k)**m.
Hint 3
There are m! bijections when m = n, and none otherwise.
Solution
Show one correct solution (try it yourself first)
from math import comb, factorial, perm
m, n = map(int, input().split())
onto = sum((-1) ** k * comb(n, k) * (n - k) ** m for k in range(n + 1))
print("all functions:", n ** m)
print("one-to-one:", perm(n, m))
print("onto:", onto)
print("bijections:", factorial(m) if m == n else 0)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step