Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Solution: Transpose text


def transpose_text(text, width):
    result = []
    for i in range(width):
        for j in range(i, len(text), width):
            result.append(text[j])
    return "".join(result)
import pytest
from transpose_text import transpose_text

@pytest.mark.parametrize("text, width, out", [
    ("a", 1, "a"),
    ("a", 2, "a"),
    ("ab", 2, "ab"),
    ("abcdefg", 2, "acegbdf"),
    ("abcdef", 2, "acebdf"),
    ("abcdefg", 3, "adgbecf"),
    ("abcdef", 3, "adbecf"),
    ("abcde", 3, "adbec"),
])
def test_1(text, width, out):
    assert transpose_text(text, width) == out