Skip to content

Commit b0e81b5

Browse files
committed
feat(algorithms, matrix): transpose matrix
1 parent 3996b3b commit b0e81b5

File tree

8 files changed

+246
-84
lines changed

8 files changed

+246
-84
lines changed
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
# Transpose
2+
3+
Take input text and output it transposed.
4+
5+
Given an input text output it transposed.
6+
7+
Roughly explained, the transpose of a matrix:
8+
9+
```
10+
ABC
11+
DEF
12+
```
13+
14+
is given by:
15+
16+
```
17+
AD
18+
BE
19+
CF
20+
```
21+
22+
Rows become columns and columns become rows. See <https://en.wikipedia.org/wiki/Transpose>.
23+
24+
If the input has rows of different lengths, this is to be solved as follows:
25+
26+
- Pad to the left with spaces.
27+
- Don't pad to the right.
28+
29+
Therefore, transposing this matrix:
30+
31+
```
32+
ABC
33+
DE
34+
```
35+
36+
results in:
37+
38+
```
39+
AD
40+
BE
41+
C
42+
```
43+
44+
And transposing:
45+
46+
```
47+
AB
48+
DEF
49+
```
50+
51+
results in:
52+
53+
```
54+
AD
55+
BE
56+
F
57+
```
58+
59+
In general, all characters from the input should also be present in the transposed output. That means that if a column
60+
in the input text contains only spaces on its bottom-most row(s), the corresponding output row should contain the spaces
61+
in its right-most column(s).
62+
63+
## Source
64+
65+
Reddit r/dailyprogrammer challenge #270 [Easy]
66+
. [https://www.reddit.com/r/dailyprogrammer/comments/4msu2x/challenge_270_easy_transpose_the_input_text](https://www.reddit.com/r/dailyprogrammer/comments/4msu2x/challenge_270_easy_transpose_the_input_text)
67+
68+
69+
--
70+
71+
# Transpose Matrix
72+
73+
You're given a 2D array of integers <span>matrix</span>. Write a function that returns the transpose of the matrix.
74+
75+
The transpose of a matrix is a flipped version of the original matrix across its main diagonal (which runs from top-left
76+
to bottom-right); it switches the row and column indices of the original matrix.
77+
78+
You can assume the input matrix always has at least 1 value; however its width and height are not necessarily the same.
79+
80+
## Examples
81+
82+
Example 1:
83+
84+
```text
85+
Input:
86+
matrix = [
87+
[1, 2],
88+
]
89+
90+
Output:
91+
[
92+
[1],
93+
[2]
94+
]
95+
```
96+
97+
Example 2:
98+
99+
```text
100+
Input:
101+
matrix = [
102+
[1, 2],
103+
[3, 4],
104+
[5, 6],
105+
]
106+
107+
Output:
108+
[
109+
[1, 3, 5],
110+
[2, 4, 6],
111+
]
112+
```
113+
114+
Example 3:
115+
116+
```text
117+
Input:
118+
matrix = [
119+
[1, 2, 3],
120+
[4, 5, 6],
121+
[7, 8, 9],
122+
]
123+
124+
Output:
125+
[
126+
[1, 4, 7],
127+
[2, 5, 8],
128+
[3, 6, 9],
129+
]
130+
```
131+
132+
## Hints
133+
134+
- The row and column indices of each entry in the matrix should be flipped. For example, the value at `matrix[1][2]` will
135+
be at `matrix[2][1]` in the transpose of the matrix.
136+
- Each column in the matrix should be become a row in the transpose of the matrix. Each row in the matrix should become
137+
a column in the transpose of the matrix.
138+
- Try iterating one column at a time, and with each column, create a row of the values to add to the transpose of the
139+
matrix.
140+
141+
## Solution
142+
143+
The transpose of a matrix `A` with dimensions `R x C` is a matrix `ans` with dimensions C x R for which `ans[c][r]` = `A[r][c]`.
144+
145+
Let's initialize a new matrix ans representing the answer. Then, we'll copy each entry of the matrix as appropriate.
146+
147+
### Complexity Analysis
148+
149+
#### Time Complexity: O(R*C)
150+
151+
Where `R` and `C` are the number of rows and columns in the given matrix `A`.
152+
153+
#### Space Complexity: O(R*C)
154+
155+
The space used by the answer.
156+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import List
2+
3+
4+
def transpose(input_lines: str) -> str:
5+
"""
6+
transposes letters in input lines like a matrix, where the columns become rows and rows
7+
become columns
8+
:param input_lines: lines to transpose
9+
:return: String with the characters transposed
10+
"""
11+
lines = input_lines.split("\n")
12+
zipped = map(list, [line.ljust(len(max(lines, key=len))) for line in lines])
13+
14+
return "\n".join("".join(line) for line in zip(*zipped)).strip()
15+
16+
17+
def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]:
18+
"""
19+
transposes a matrix by making the columns the rows and the rows the columns
20+
Args:
21+
matrix: matrix to transpose
22+
Returns:
23+
Transposed matrix
24+
"""
25+
if not matrix:
26+
return []
27+
28+
n_rows = len(matrix)
29+
n_cols = len(matrix[0])
30+
31+
transposed_matrix = [[0] * n_rows for _ in range(n_cols)]
32+
33+
for row in range(n_rows):
34+
for col in range(n_cols):
35+
value = matrix[row][col]
36+
transposed_matrix[col][row] = value
37+
38+
return transposed_matrix

tests/algorithms/test_transpose.py renamed to algorithms/matrix/transpose/test_transpose.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import unittest
22

3-
from algorithms.transpose import transpose
4-
5-
# test cases adapted from `x-common//canonical-data.json` @ version: 1.0.0
3+
from algorithms.matrix.transpose import transpose
64

75

86
class TransposeTests(unittest.TestCase):
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import unittest
2+
from typing import List
3+
from parameterized import parameterized
4+
from algorithms.matrix.transpose import transpose_matrix
5+
6+
TRANSPOSE_MATRIX_TEST_CASES = [
7+
(
8+
[
9+
[1, 2],
10+
],
11+
[[1], [2]],
12+
),
13+
(
14+
[
15+
[1, 2],
16+
[3, 4],
17+
[5, 6],
18+
],
19+
[
20+
[1, 3, 5],
21+
[2, 4, 6],
22+
],
23+
),
24+
(
25+
[
26+
[1, 2, 3],
27+
[4, 5, 6],
28+
[7, 8, 9],
29+
],
30+
[
31+
[1, 4, 7],
32+
[2, 5, 8],
33+
[3, 6, 9],
34+
],
35+
),
36+
]
37+
38+
39+
class TransposeMatrixTestCase(unittest.TestCase):
40+
@parameterized.expand(TRANSPOSE_MATRIX_TEST_CASES)
41+
def test_transpose_matrix(self, matrix: List[List[int]], expected: List[List[int]]):
42+
actual = transpose_matrix(matrix)
43+
self.assertEqual(actual, expected)
44+
45+
46+
if __name__ == "__main__":
47+
unittest.main()

algorithms/transpose/README.md

Lines changed: 0 additions & 67 deletions
This file was deleted.

algorithms/transpose/__init__.py

Lines changed: 0 additions & 11 deletions
This file was deleted.

bit_manipulation/sum_two_integers/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ def integer_addition(a: int, b: int):
2727

2828
def integer_addition_2(a: int, b: int) -> int:
2929
mask = 0xFFFFFFFF
30-
max_int = 2 ** 31 - 1
30+
max_int = 2**31 - 1
3131
while b != 0:
3232
sum_ = (a ^ b) & mask
3333
carry = (a & b) & mask
3434
a = sum_
3535
b = carry << 1
36-
return a if a <= max_int else ~(a ^ mask)
36+
return a if a <= max_int else ~(a ^ mask)

bit_manipulation/sum_two_integers/test_sum_of_two_integers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
(2147483647, 1, -2147483648),
1414
]
1515

16+
1617
class SumOfTwoIntegersTestCase(unittest.TestCase):
1718
@parameterized.expand(SUM_OF_TWO_INTEGERS_TEST_CASES)
1819
def test_integer_addition(self, a: int, b: int, expected: int):
@@ -25,5 +26,5 @@ def test_integer_addition_2(self, a: int, b: int, expected: int):
2526
self.assertEqual(result, expected)
2627

2728

28-
if __name__ == '__main__':
29+
if __name__ == "__main__":
2930
unittest.main()

0 commit comments

Comments
 (0)