Compose a function and find its inverse

A function from the numbers 1 to n to themselves can be written as the list of its images. Your program composes it with itself and finds the inverse when there is one.

What to build

A program that reports whether f is a bijection, prints f after f, and prints the inverse.

Requirements

  • Read n, then a line with f(1), ..., f(n); every value is between 1 and n.
  • Print bijective: yes or bijective: no.
  • Print f after f: and the values f(f(1)), ..., f(f(n)).
  • Print inverse: and the values g(1), ..., g(n) of the inverse function if f is a bijection, or inverse: none if it is not.

Input

The first line has n. The second line has n whole numbers.

Output

Three lines.

Constraints

1 ≤ n ≤ 10.

Example

Input:

3
2 3 1

Output:

bijective: yes
f after f: 3 1 2
inverse: 3 1 2

Why it works

A function on 1 to n is a bijection exactly when its values are all different (and so cover 1 to n). The inverse undoes f, so g(f(i)) = i, which is found by placing i at position f(i). The composition applies f twice.

Examples

Example 1 · Input
3
2 3 1
Expected output
bijective: yes
f after f: 3 1 2
inverse: 3 1 2
Example 2 · Input
3
1 1 2
Expected output
bijective: no
f after f: 1 1 1
inverse: none

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Store f as a list where f[i - 1] is the image of i.

Hint 2

The composition f after f has the image f[f[i] - 1] for each i.

Hint 3

If the images are exactly 1 to n, each used once, f is a bijection; the inverse g satisfies g[f(i)] = i.

Solution

Show one correct solution (try it yourself first)
n = int(input())
f = list(map(int, input().split()))
ff = [f[f[i] - 1] for i in range(n)]
bij = sorted(f) == list(range(1, n + 1))
print("bijective:", "yes" if bij else "no")
print("f after f:", *ff)
if bij:
    g = [0] * n
    for i in range(n):
        g[f[i] - 1] = i + 1
    print("inverse:", *g)
else:
    print("inverse: none")

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Functions →