-
Notifications
You must be signed in to change notification settings - Fork 2
feat(algorithms matrix): transpose a matrix #184
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| # Transpose | ||
|
|
||
| Take input text and output it transposed. | ||
|
|
||
| Given an input text output it transposed. | ||
|
|
||
| Roughly explained, the transpose of a matrix: | ||
|
|
||
| ``` | ||
| ABC | ||
| DEF | ||
| ``` | ||
|
|
||
| is given by: | ||
|
|
||
| ``` | ||
| AD | ||
| BE | ||
| CF | ||
| ``` | ||
|
|
||
| Rows become columns and columns become rows. See <https://en.wikipedia.org/wiki/Transpose>. | ||
|
|
||
| If the input has rows of different lengths, this is to be solved as follows: | ||
|
|
||
| - Pad to the left with spaces. | ||
| - Don't pad to the right. | ||
|
|
||
| Therefore, transposing this matrix: | ||
|
|
||
| ``` | ||
| ABC | ||
| DE | ||
| ``` | ||
|
|
||
| results in: | ||
|
|
||
| ``` | ||
| AD | ||
| BE | ||
| C | ||
| ``` | ||
|
|
||
| And transposing: | ||
|
|
||
| ``` | ||
| AB | ||
| DEF | ||
| ``` | ||
|
|
||
| results in: | ||
|
|
||
| ``` | ||
|
Comment on lines
+9
to
+53
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Specify code fence languages to satisfy markdown linting. The fenced blocks in this range should include a language identifier (e.g. 💡 Proposed fix-```
+```text
ABC
DEF@@ @@ @@ 🧰 Tools🪛 markdownlint-cli2 (0.21.0)[warning] 9-9: Fenced code blocks should have a language specified (MD040, fenced-code-language) [warning] 16-16: Fenced code blocks should have a language specified (MD040, fenced-code-language) [warning] 31-31: Fenced code blocks should have a language specified (MD040, fenced-code-language) [warning] 38-38: Fenced code blocks should have a language specified (MD040, fenced-code-language) [warning] 46-46: Fenced code blocks should have a language specified (MD040, fenced-code-language) [warning] 53-53: Fenced code blocks should have a language specified (MD040, fenced-code-language) 🤖 Prompt for AI Agents |
||
| AD | ||
| BE | ||
| F | ||
| ``` | ||
|
|
||
| In general, all characters from the input should also be present in the transposed output. That means that if a column | ||
| in the input text contains only spaces on its bottom-most row(s), the corresponding output row should contain the spaces | ||
| in its right-most column(s). | ||
|
|
||
| ## Source | ||
|
|
||
| Reddit r/dailyprogrammer challenge #270 [Easy] | ||
| . [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) | ||
|
|
||
|
|
||
| -- | ||
|
|
||
| # Transpose Matrix | ||
|
|
||
| You're given a 2D array of integers <span>matrix</span>. Write a function that returns the transpose of the matrix. | ||
|
|
||
| The transpose of a matrix is a flipped version of the original matrix across its main diagonal (which runs from top-left | ||
| to bottom-right); it switches the row and column indices of the original matrix. | ||
|
|
||
| You can assume the input matrix always has at least 1 value; however its width and height are not necessarily the same. | ||
|
|
||
| ## Examples | ||
|
|
||
| Example 1: | ||
|
|
||
| ```text | ||
| Input: | ||
| matrix = [ | ||
| [1, 2], | ||
| ] | ||
|
|
||
| Output: | ||
| [ | ||
| [1], | ||
| [2] | ||
| ] | ||
| ``` | ||
|
|
||
| Example 2: | ||
|
|
||
| ```text | ||
| Input: | ||
| matrix = [ | ||
| [1, 2], | ||
| [3, 4], | ||
| [5, 6], | ||
| ] | ||
|
|
||
| Output: | ||
| [ | ||
| [1, 3, 5], | ||
| [2, 4, 6], | ||
| ] | ||
| ``` | ||
|
|
||
| Example 3: | ||
|
|
||
| ```text | ||
| Input: | ||
| matrix = [ | ||
| [1, 2, 3], | ||
| [4, 5, 6], | ||
| [7, 8, 9], | ||
| ] | ||
|
|
||
| Output: | ||
| [ | ||
| [1, 4, 7], | ||
| [2, 5, 8], | ||
| [3, 6, 9], | ||
| ] | ||
| ``` | ||
|
|
||
| ## Hints | ||
|
|
||
| - The row and column indices of each entry in the matrix should be flipped. For example, the value at `matrix[1][2]` will | ||
| be at `matrix[2][1]` in the transpose of the matrix. | ||
| - Each column in the matrix should be become a row in the transpose of the matrix. Each row in the matrix should become | ||
| a column in the transpose of the matrix. | ||
|
Comment on lines
+136
to
+137
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Minor wording typo in hints section. At Line 136, “should be become” should be “should become”. 🤖 Prompt for AI Agents |
||
| - Try iterating one column at a time, and with each column, create a row of the values to add to the transpose of the | ||
| matrix. | ||
|
|
||
| ## Solution | ||
|
|
||
| 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]`. | ||
|
|
||
| Let's initialize a new matrix ans representing the answer. Then, we'll copy each entry of the matrix as appropriate. | ||
|
|
||
| ### Complexity Analysis | ||
|
|
||
| #### Time Complexity: O(R*C) | ||
|
|
||
| Where `R` and `C` are the number of rows and columns in the given matrix `A`. | ||
|
|
||
| #### Space Complexity: O(R*C) | ||
|
|
||
| The space used by the answer. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| from typing import List | ||
|
|
||
|
|
||
| def transpose(input_lines: str) -> str: | ||
| """ | ||
| transposes letters in input lines like a matrix, where the columns become rows and rows | ||
| become columns | ||
| :param input_lines: lines to transpose | ||
| :return: String with the characters transposed | ||
| """ | ||
| lines = input_lines.split("\n") | ||
| zipped = map(list, [line.ljust(len(max(lines, key=len))) for line in lines]) | ||
|
|
||
| return "\n".join("".join(line) for line in zip(*zipped)).strip() | ||
|
Comment on lines
+11
to
+14
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
At Line 14, 💡 Proposed fix def transpose(input_lines: str) -> str:
@@
- lines = input_lines.split("\n")
- zipped = map(list, [line.ljust(len(max(lines, key=len))) for line in lines])
-
- return "\n".join("".join(line) for line in zip(*zipped)).strip()
+ lines = input_lines.split("\n")
+ max_cols = max(len(line) for line in lines) if lines else 0
+ output_lines: List[str] = []
+
+ for col in range(max_cols):
+ row_chars: List[str] = []
+ for row_idx, line in enumerate(lines):
+ if col < len(line):
+ row_chars.append(line[col])
+ elif any(col < len(next_line) for next_line in lines[row_idx + 1 :]):
+ row_chars.append(" ")
+ output_lines.append("".join(row_chars))
+
+ return "\n".join(output_lines)🤖 Prompt for AI Agents |
||
|
|
||
|
|
||
| def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: | ||
| """ | ||
| transposes a matrix by making the columns the rows and the rows the columns | ||
| Args: | ||
| matrix: matrix to transpose | ||
| Returns: | ||
| Transposed matrix | ||
| """ | ||
| if not matrix: | ||
| return [] | ||
|
|
||
| n_rows = len(matrix) | ||
| n_cols = len(matrix[0]) | ||
|
|
||
| transposed_matrix = [[0] * n_rows for _ in range(n_cols)] | ||
|
|
||
| for row in range(n_rows): | ||
| for col in range(n_cols): | ||
| value = matrix[row][col] | ||
| transposed_matrix[col][row] = value | ||
|
Comment on lines
+28
to
+36
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Validate rectangular input in At Line 35, jagged input can trigger 💡 Proposed fix n_rows = len(matrix)
n_cols = len(matrix[0])
+ if any(len(row) != n_cols for row in matrix):
+ raise ValueError("All rows in `matrix` must have the same length")🤖 Prompt for AI Agents |
||
|
|
||
| return transposed_matrix | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| import unittest | ||
| from typing import List | ||
| from parameterized import parameterized | ||
| from algorithms.matrix.transpose import transpose_matrix | ||
|
|
||
| TRANSPOSE_MATRIX_TEST_CASES = [ | ||
| ( | ||
| [ | ||
| [1, 2], | ||
| ], | ||
| [[1], [2]], | ||
| ), | ||
| ( | ||
| [ | ||
| [1, 2], | ||
| [3, 4], | ||
| [5, 6], | ||
| ], | ||
| [ | ||
| [1, 3, 5], | ||
| [2, 4, 6], | ||
| ], | ||
| ), | ||
| ( | ||
| [ | ||
| [1, 2, 3], | ||
| [4, 5, 6], | ||
| [7, 8, 9], | ||
| ], | ||
| [ | ||
| [1, 4, 7], | ||
| [2, 5, 8], | ||
| [3, 6, 9], | ||
| ], | ||
| ), | ||
| ] | ||
|
|
||
|
|
||
| class TransposeMatrixTestCase(unittest.TestCase): | ||
| @parameterized.expand(TRANSPOSE_MATRIX_TEST_CASES) | ||
| def test_transpose_matrix(self, matrix: List[List[int]], expected: List[List[int]]): | ||
| actual = transpose_matrix(matrix) | ||
| self.assertEqual(actual, expected) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
This file was deleted.
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Padding direction is documented incorrectly.
At Line 26, the rule should be right-padding, not left-padding, to match the examples and implementation behaviour.
💡 Proposed fix
📝 Committable suggestion
🤖 Prompt for AI Agents