115 lines
2.6 KiB
Python
115 lines
2.6 KiB
Python
# Prog3B/compute.py
|
||
|
||
"""Matrix transpose implementation.
|
||
|
||
The function `transpose` accepts a 2‑D list `matrix` and returns a new
|
||
2‑D list where rows and columns are swapped. The implementation uses
|
||
simple for‑loops and basic list operations to stay within the beginner
|
||
Python skill level.
|
||
|
||
Example
|
||
-------
|
||
>>> transpose([[1, 2, 3], [4, 5, 6]])
|
||
[[1, 4], [2, 5], [3, 6]]
|
||
|
||
"""
|
||
|
||
from typing import List, Any
|
||
import math
|
||
|
||
|
||
def transpose(matrix: List[List[Any]]) -> List[List[Any]]:
|
||
"""Return the transpose of a rectangular matrix.
|
||
|
||
Parameters
|
||
----------
|
||
matrix: list of list
|
||
A non‑empty 2‑D list where each sub‑list represents a row. All
|
||
rows are assumed to be the same length.
|
||
|
||
Returns
|
||
-------
|
||
list of list
|
||
A new matrix where the i‑th row of the result contains the i‑th
|
||
column of the input.
|
||
"""
|
||
if not matrix:
|
||
return []
|
||
|
||
rows = len(matrix)
|
||
cols = len(matrix[0])
|
||
|
||
# initialise result with correct dimensions
|
||
result: List[List[Any]] = [[0] * rows for _ in range(cols)]
|
||
|
||
for i in range(rows):
|
||
for j in range(cols):
|
||
result[j][i] = matrix[i][j]
|
||
|
||
return result
|
||
|
||
|
||
def rotate(matrix: List[List[Any]]) -> List[List[Any]]:
|
||
"""Return a new matrix rotated 90 degrees clockwise.
|
||
|
||
The original matrix is not modified.
|
||
|
||
Parameters
|
||
----------
|
||
matrix: list of list
|
||
A rectangular matrix.
|
||
|
||
Returns
|
||
-------
|
||
list of list
|
||
Rotated matrix.
|
||
"""
|
||
if not matrix:
|
||
return []
|
||
inter = transpose(matrix)
|
||
rows = len(inter); cols = len(inter[0])
|
||
result: List[List[Any]] = [[0] * rows for _ in range(cols)]
|
||
for i in range(cols):
|
||
for j in range(rows):
|
||
result[i][j] = inter[rows - 1 - j][i]
|
||
return result
|
||
|
||
def rot_2D(theta):
|
||
"""Erzeugt eine Rotationsmatrix für einen Winkel."""
|
||
|
||
return [
|
||
[math.cos(theta), -math.sin(theta)],
|
||
[math.sin(theta), math.cos(theta)]
|
||
]
|
||
|
||
def matmul(A, B):
|
||
"""Multipliziert zwei Matrizen."""
|
||
|
||
rows_A = len(A)
|
||
cols_A = len(A[0])
|
||
cols_B = len(B[0])
|
||
|
||
if cols_A != len(B):
|
||
raise ValueError("Matrizen können nicht multipliziert werden")
|
||
|
||
result = [[0] * cols_B for _ in range(rows_A)]
|
||
|
||
for i in range(rows_A):
|
||
for j in range(cols_B):
|
||
for k in range(cols_A):
|
||
result[i][j] += A[i][k] * B[k][j]
|
||
|
||
return result
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# simple demonstration / sanity check
|
||
sample = [[1, 2, 3], [4, 5, 6]]
|
||
print("Input:")
|
||
print(sample)
|
||
print("\nTransposed:")
|
||
print(transpose(sample))
|
||
print("\nRotated:")
|
||
print(rotate(sample))
|
||
|