You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
"""
|
|
A matrix is a two-dimensional collection of numbers. Math convention uses capital
|
|
letter to represent matrices.
|
|
|
|
2 x 3 Matrix
|
|
A = [[1, 2, 3], [4, 5, 6]]
|
|
|
|
3 x 2 Matrix
|
|
B = [[1, 2], [3, 4], [5, 6]]
|
|
|
|
"""
|
|
from typing import List, Tuple, Callable
|
|
|
|
|
|
def shape(A: List[List[float]]) -> Tuple[int, int]:
|
|
"""Calculates the shape of a matrix.
|
|
|
|
If matrix has n rows and k columns we call it a n x k matrix."""
|
|
num_rows = len(A)
|
|
num_columns = len(A[0]) if A else 0
|
|
return num_rows, num_columns
|
|
|
|
|
|
def get_row(A: List[List[float]], i) -> List[float]:
|
|
"""Returns the ith row from a matrix."""
|
|
return A[i]
|
|
|
|
|
|
def get_column(A: List[List[float]], j) -> List[float]:
|
|
"""Returns the jth column from a matrix."""
|
|
return [A_i[j] for A_i in A]
|
|
|
|
|
|
def make_matrix(
|
|
num_rows: int, num_colums: int, entry_fn: Callable
|
|
) -> List[List[float]]:
|
|
"""Creates a n x k matrix whose (i, j)th entry is entry(i, j)."""
|
|
return [[entry_fn(i, j) for j in range(num_colums)] for i in range(num_rows)]
|
|
|
|
|
|
def is_diagonal(i , j) -> int:
|
|
"""1's on the 'diagonal', 0's everywhere else."""
|
|
return 1 if i == j else 0 |