Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,9 @@
* [Test Best Meeting Point](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/matrix/best_meeting_point/test_best_meeting_point.py)
* Isvalidsudoku
* [Test Is Valid Sudoku](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/matrix/isvalidsudoku/test_is_valid_sudoku.py)
* Transpose
* [Test Transpose](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/matrix/transpose/test_transpose.py)
* [Test Transpose Matrix](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/matrix/transpose/test_transpose_matrix.py)
* Memoization
* [Fibonacci](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/memoization/fibonacci.py)
* [Petethebaker](https://github.com/BrianLusina/PythonSnips/blob/master/algorithms/petethebaker.py)
Expand Down Expand Up @@ -1105,7 +1108,6 @@
* [Test Robot Name](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_robot_name.py)
* [Test Say Number](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_say_number.py)
* [Test Space Age](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_space_age.py)
* [Test Transpose](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_transpose.py)
* [Test Tree Building](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_tree_building.py)
* [Test Variable Length Qty](https://github.com/BrianLusina/PythonSnips/blob/master/tests/algorithms/test_variable_length_qty.py)
* Cryptography
Expand Down
156 changes: 156 additions & 0 deletions algorithms/matrix/transpose/README.md
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.
Comment on lines +24 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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
-- Pad to the left with spaces.
+- Pad to the right with spaces.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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.
If the input has rows of different lengths, this is to be solved as follows:
- Pad to the right with spaces.
- Don't pad to the right.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@algorithms/matrix/transpose/README.md` around lines 24 - 27, The README for
the matrix transpose exercise documents padding direction incorrectly: the
bullet that reads "Pad to the left with spaces." should be changed to "Pad to
the right with spaces." to match the examples and implementation; update that
sentence in the transpose README so it explicitly states right-padding (and
leave the "Don't pad to the right." line removed or corrected accordingly).


Therefore, transposing this matrix:

```
ABC
DE
```

results in:

```
AD
BE
C
```

And transposing:

```
AB
DEF
```

results in:

```
Comment on lines +9 to +53
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Specify code fence languages to satisfy markdown linting.

The fenced blocks in this range should include a language identifier (e.g. text) to resolve MD040 warnings.

💡 Proposed fix
-```
+```text
 ABC
 DEF

@@
- +text
AD
BE
CF

@@
-```
+```text
ABC
DE

@@
- +text
AD
BE
C

@@
-```
+```text
AB
DEF

@@
- +text
AD
BE
F

🧰 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
Verify each finding against the current code and only fix it if needed.

In `@algorithms/matrix/transpose/README.md` around lines 9 - 53, The fenced code
blocks in README.md examples (the blocks containing "ABC\nDEF", "AD\nBE\nCF",
"ABC\nDE", "AD\nBE\nC", "AB\nDEF", and the final "AD\nBE\n F" example) need
explicit language identifiers to satisfy markdown linting; update each opening
triple-backtick so it reads ```text instead of ``` for those specific examples
so MD040 warnings are resolved.

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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Minor wording typo in hints section.

At Line 136, “should be become” should be “should become”.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@algorithms/matrix/transpose/README.md` around lines 136 - 137, Fix the minor
wording typo in the hints section by changing the phrase "should be become" to
"should become" in the sentence that currently reads "Each column in the matrix
should be become a row in the transpose of the matrix." in the README.md
transpose hints; ensure the corrected sentence reads "Each column in the matrix
should become a row in the transpose of the matrix." to maintain clarity.

- 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.

38 changes: 38 additions & 0 deletions algorithms/matrix/transpose/__init__.py
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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

transpose removes meaningful whitespace with global strip().

At Line 14, .strip() can delete valid characters (e.g. leading spaces in the first output row, or all-space outputs), which breaks the transpose contract.

💡 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
Verify each finding against the current code and only fix it if needed.

In `@algorithms/matrix/transpose/__init__.py` around lines 11 - 14, The final
.strip() call in the transpose implementation removes meaningful
leading/trailing spaces (breaking outputs that start with spaces or consist only
of spaces); update the return of the function (the expression that currently
does "return \"\\n\".join(...).strip()") to not use .strip() — either remove it
entirely or replace it with .rstrip("\n") if you only want to drop a trailing
newline, so that leading spaces and all-space rows are preserved by the
transpose function.



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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Validate rectangular input in transpose_matrix.

At Line 35, jagged input can trigger IndexError. It is safer to fail fast with a clear ValueError.

💡 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
Verify each finding against the current code and only fix it if needed.

In `@algorithms/matrix/transpose/__init__.py` around lines 28 - 36, The function
transpose_matrix currently assumes rectangular input and uses n_cols =
len(matrix[0]) then indexes each row, which can raise IndexError for jagged
lists; before creating transposed_matrix, compute n_rows = len(matrix) and
n_cols = len(matrix[0]) and then validate every row in matrix has length ==
n_cols (e.g., loop over rows and compare len(row)), and if any differ raise a
ValueError with a clear message (e.g., "transpose_matrix expects a rectangular
matrix; row X has length Y != n_cols"). Ensure this validation occurs before
allocating transposed_matrix and before the nested loop that assigns
transposed_matrix[col][row] = value.


return transposed_matrix
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import unittest

from algorithms.transpose import transpose

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


class TransposeTests(unittest.TestCase):
Expand Down
47 changes: 47 additions & 0 deletions algorithms/matrix/transpose/test_transpose_matrix.py
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()
67 changes: 0 additions & 67 deletions algorithms/transpose/README.md

This file was deleted.

11 changes: 0 additions & 11 deletions algorithms/transpose/__init__.py

This file was deleted.

4 changes: 2 additions & 2 deletions bit_manipulation/sum_two_integers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ def integer_addition(a: int, b: int):

def integer_addition_2(a: int, b: int) -> int:
mask = 0xFFFFFFFF
max_int = 2 ** 31 - 1
max_int = 2**31 - 1
while b != 0:
sum_ = (a ^ b) & mask
carry = (a & b) & mask
a = sum_
b = carry << 1
return a if a <= max_int else ~(a ^ mask)
return a if a <= max_int else ~(a ^ mask)
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
(2147483647, 1, -2147483648),
]


class SumOfTwoIntegersTestCase(unittest.TestCase):
@parameterized.expand(SUM_OF_TWO_INTEGERS_TEST_CASES)
def test_integer_addition(self, a: int, b: int, expected: int):
Expand All @@ -25,5 +26,5 @@ def test_integer_addition_2(self, a: int, b: int, expected: int):
self.assertEqual(result, expected)


if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()
Loading