Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Last active December 6, 2020 19:31
Show Gist options
  • Save vlad-bezden/84b0418c244c4a3928fa41efd85f9040 to your computer and use it in GitHub Desktop.
Save vlad-bezden/84b0418c244c4a3928fa41efd85f9040 to your computer and use it in GitHub Desktop.
Transform Matrix 90 degrees
from pprint import pprint as pp
def transpose(self, A: list[list[int]]) -> list[list[int]]:
# using list comprehension
return [[row[c] for row in A] for c in range(len(A[0]))]
def transpose(self, A: list[list[int]]) -> list[list[int]]:
# using zip
return [list(x) for x in zip(*A)]
def transpose(self, A: list[list[int]]) -> list[list[int]]:
# pure manual implementation
rows = len(A)
cols = len(A[0])
T = [[0] * rows for _ in range(cols)]
for r in range(rows):
for c in range(cols):
T[c][r] = A[r][c]
return T
# create a matrix
rows, cols = (5, 10)
data = [[j + cols * i for j in range(cols)] for i in range(rows)]
print("Data before transform")
pp(data)
data_t = transform(data)
print("Transformed data using loop")
pp(data_t)
data_t = [list(x) for x in zip(*data)]
print("Transformed data using zip")
pp(data_t)
"""
Data before transform
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]
Transformed data using loop
[[0, 10, 20, 30, 40],
[1, 11, 21, 31, 41],
[2, 12, 22, 32, 42],
[3, 13, 23, 33, 43],
[4, 14, 24, 34, 44],
[5, 15, 25, 35, 45],
[6, 16, 26, 36, 46],
[7, 17, 27, 37, 47],
[8, 18, 28, 38, 48],
[9, 19, 29, 39, 49]]
Transformed data using zip
[[0, 10, 20, 30, 40],
[1, 11, 21, 31, 41],
[2, 12, 22, 32, 42],
[3, 13, 23, 33, 43],
[4, 14, 24, 34, 44],
[5, 15, 25, 35, 45],
[6, 16, 26, 36, 46],
[7, 17, 27, 37, 47],
[8, 18, 28, 38, 48],
[9, 19, 29, 39, 49]]
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment