Transpose Matrix in Python
def main():
"""
Prints the transpose of a matrix.
"""
# Get the dimensions of the matrix
row_count = int(input("Enter the number of rows: "))
col_count = int(input("Enter the number of cols: "))
# Read the matrix from the user
print("Enter the matrix:")
matrix = read_matrix(row_count, col_count)
# Transpose the matrix
transposed = transpose(matrix)
print("The transpose is: ")
print_matrix(transposed)
def transpose(matrix: list[list[int]]):
"""
Transposes a matrix.
"""
m, n = len(matrix), len(matrix[0])
matrix_t = [[0] * m for _ in range(n)]
# Transpose the matrix
for r in range(m):
for c in range(n):
matrix_t[c][r] = matrix[r][c]
return matrix_t
def read_matrix(row_count: int, col_count: int):
"""
Reads a matrix from the console.
"""
matrix: list[list[int]] = []
for _ in range(row_count):
row = list(map(int, input().split()[:col_count]))
matrix.append(row)
return matrix
def print_matrix(matrix: list[list[int]]):
"""
Prints a matrix to the console.
"""
for row in matrix:
for element in row:
print(element, end=" ")
print()
if __name__ == "__main__":
main()