coordinates is a two dimensional matrix: [[x, y], [x, y], ...] number of points you want to use >>> points_to_polynomial([]) Traceback (most recent call last): ... ValueError: The program cannot work out a fitting polynomial. >>> points_to_polynomial([[]]) Trace
(coordinates: list[list[int]])
| 1 | def points_to_polynomial(coordinates: list[list[int]]) -> str: |
| 2 | """ |
| 3 | coordinates is a two dimensional matrix: [[x, y], [x, y], ...] |
| 4 | number of points you want to use |
| 5 | |
| 6 | >>> points_to_polynomial([]) |
| 7 | Traceback (most recent call last): |
| 8 | ... |
| 9 | ValueError: The program cannot work out a fitting polynomial. |
| 10 | >>> points_to_polynomial([[]]) |
| 11 | Traceback (most recent call last): |
| 12 | ... |
| 13 | ValueError: The program cannot work out a fitting polynomial. |
| 14 | >>> points_to_polynomial([[1, 0], [2, 0], [3, 0]]) |
| 15 | 'f(x)=x^2*0.0+x^1*-0.0+x^0*0.0' |
| 16 | >>> points_to_polynomial([[1, 1], [2, 1], [3, 1]]) |
| 17 | 'f(x)=x^2*0.0+x^1*-0.0+x^0*1.0' |
| 18 | >>> points_to_polynomial([[1, 3], [2, 3], [3, 3]]) |
| 19 | 'f(x)=x^2*0.0+x^1*-0.0+x^0*3.0' |
| 20 | >>> points_to_polynomial([[1, 1], [2, 2], [3, 3]]) |
| 21 | 'f(x)=x^2*0.0+x^1*1.0+x^0*0.0' |
| 22 | >>> points_to_polynomial([[1, 1], [2, 4], [3, 9]]) |
| 23 | 'f(x)=x^2*1.0+x^1*-0.0+x^0*0.0' |
| 24 | >>> points_to_polynomial([[1, 3], [2, 6], [3, 11]]) |
| 25 | 'f(x)=x^2*1.0+x^1*-0.0+x^0*2.0' |
| 26 | >>> points_to_polynomial([[1, -3], [2, -6], [3, -11]]) |
| 27 | 'f(x)=x^2*-1.0+x^1*-0.0+x^0*-2.0' |
| 28 | >>> points_to_polynomial([[1, 5], [2, 2], [3, 9]]) |
| 29 | 'f(x)=x^2*5.0+x^1*-18.0+x^0*18.0' |
| 30 | >>> points_to_polynomial([[1, 1], [1, 2], [1, 3]]) |
| 31 | 'x=1' |
| 32 | >>> points_to_polynomial([[1, 1], [2, 2], [2, 2]]) |
| 33 | Traceback (most recent call last): |
| 34 | ... |
| 35 | ValueError: The program cannot work out a fitting polynomial. |
| 36 | """ |
| 37 | if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates): |
| 38 | raise ValueError("The program cannot work out a fitting polynomial.") |
| 39 | |
| 40 | if len({tuple(pair) for pair in coordinates}) != len(coordinates): |
| 41 | raise ValueError("The program cannot work out a fitting polynomial.") |
| 42 | |
| 43 | set_x = {x for x, _ in coordinates} |
| 44 | if len(set_x) == 1: |
| 45 | return f"x={coordinates[0][0]}" |
| 46 | |
| 47 | if len(set_x) != len(coordinates): |
| 48 | raise ValueError("The program cannot work out a fitting polynomial.") |
| 49 | |
| 50 | x = len(coordinates) |
| 51 | |
| 52 | # put the x and x to the power values in a matrix |
| 53 | matrix: list[list[float]] = [ |
| 54 | [ |
| 55 | coordinates[count_of_line][0] ** (x - (count_in_line + 1)) |
| 56 | for count_in_line in range(x) |
| 57 | ] |
| 58 | for count_of_line in range(x) |
| 59 | ] |
| 60 |
no test coverage detected