Testing a candidate eigenvector needs only one matrix-vector product and a comparison.
What to build
Say whether a vector is an eigenvector of a matrix and, if so, give its eigenvalue.
Requirements
- Read n, the n × n matrix and the vector v.
- Compute A·v and print it.
- If A·v = λ·v for some number λ, print
eigenvector lambda L; otherwise printnot an eigenvector.
Input
A whole number n (2 to 4), n lines of n whole numbers, then a line with n whole numbers (the vector v, not all zeros).
Output
Two lines: Av = followed by the entries separated by spaces, then eigenvector lambda L (L a whole number or fraction) or not an eigenvector.
Constraints
All entries are between -20 and 20.
Example
Input:
2
2 1
1 2
1 1
Output:
Av = 3 3
eigenvector lambda 3
Why it works
If v is an eigenvector then A·v is v scaled by λ. Looking at one non-zero entry fixes λ, and the other entries must then agree. If they do not, A turns v off its line, so it is not an eigenvector.
Examples
2 2 1 1 2 1 1
Av = 3 3 eigenvector lambda 3
2 2 1 1 2 1 0
Av = 2 1 not an eigenvector
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Compute A·v. If v has a non-zero entry v[i], the only possible λ is (A·v)[i] ÷ v[i].
Hint 2
Use Fraction so the comparison is exact, then check that A·v equals λ times v in every entry.
Hint 3
Print the Fraction with `str` so 3 prints as 3 and 3/2 as 3/2.
Solution
Show one correct solution (try it yourself first)
from fractions import Fraction
n = int(input())
A = [[int(x) for x in input().split()] for _ in range(n)]
v = [int(x) for x in input().split()]
w = [sum(a * b for a, b in zip(row, v)) for row in A]
print("Av =", *w)
i = next(k for k in range(n) if v[k] != 0)
lam = Fraction(w[i], v[i])
if all(w[k] == lam * v[k] for k in range(n)):
print("eigenvector lambda", lam)
else:
print("not an eigenvector")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step