Не получается повернуть строку на 90 градусов и сделать из неё "квадратную строку" в python3

Я столкнулся с трудностью, работая над задачей с сайта codewars.com.

Условие задачи

Квадратная строка - это строка, состоящая из n строк, каждая из которых содержит n символов. Например:

s = "abcd\nefgh\nijkl\nmnop"    # это квадратная строка размера 4

Мы будем использовать квадратные строки для кодирования и декодирования текста. Чтобы упростить задачу, предположим, что исходный текст не содержит символ '\n'.

Кодирование:

  • Загрузите исходный текст t длиной l.
  • Найдите наименьшее целое число n, такое что n * n >= l.
  • Дополните исходный текст t символом с ASCII-кодом 11 (будем предполагать, что этот символ в нем отсутствует), чтобы его длина стала равна n * n.
  • Преобразуйте новый t в квадратную строку s размера n, вставив символы '\n' в нужных местах.
  • Выполните поворот строки s по часовой стрелке на 90 градусов - на этом кодирование завершено.

Моё решение

Создал функцию для нахождения такого числа "n":

from collections import deque

st = ("What do you remember? When I looked at his streaky glasses, I wanted "
         "to leave him. And before that? He stole those cherries for me at midnight. We were walking "
         "in the rain and I loved him. And before that? I saw him coming "
         "toward me that time at the picnic, edgy, foreign.")

def find_n(st):
    k = 2
    while True:
        n = len(st) // k
        if len(st) <= k*k:
            return k   # st , k, len(st)
        else:
            st = st + chr(11)
            k += 1
print(find_n(st))

Получилось для такой строки n = 17:

len(st) == 272
17*16 == 272   # пришлось добавлять ascii-код 11 к строке 17 раз 
17*17 == 289   # получился расчёт для "квадратной строки", т.е. 17 раз по 17 символов

Далее разбиваем строку по 17 символов

def grouper(st, n):
    args = [iter(st)] * n
    return zip(*args)

# ls = [''.join(i) for i in grouper(st, n)]

def code(st):
    n = find_n(st)
    l = [''.join(i) for i in grouper(st, n)]
    print(l)
    ll = []
    for el in l:
        ll.append(el + '\n')  # ll.append(chr(11) + el + '\n')
    print(''.join(ll))
    d = deque(ll)
    d.rotate(1)
    print(d)

print(code(st))

Вот правильный ответ:

data1Sol = ("\x0bctg?.nadr d gdbW\n\x0b,i    lnis tl eh\n\x0b mtIAakietboaara\n\x0beeo nnigsoe st?t\n"
"\x0bd wsddnh lfls   \n\x0bgaaa  gtfeoeehWd\n"
"\x0bytrwbI .o rasiho\n\x0b, d e i rtev,se \n\x0b t hflnW h e  ny\n\x0bfhmioo emot Is o\n\x0boeemrvt eshh tIu\n\x0br   eehw eaiwr  \n"
"\x0beptc deea tmaelr\n\x0biihot  rtc?.naoe\n\x0bgcamhhre h  tkom\n\x0bnntiaia meHAeyke\n\x0b.i ntmiwirend em")

Вот мой ответ - даже не подставляя \x0b в начало каждой 17 символьный строки:

What do you remem
ber? When I looke
d at his streaky 
glasses, I wanted
 to leave him. An
d before that? He
 stole those cher
ries for me at mi
dnight. We were w
alking in the rai
n and I loved him
. And before that
? I saw him comin
g toward me that 
time at the picni
c, edgy, foreign.

deque(['c, edgy, foreign.\n', 'What do you remem\n', 'ber? When I looke\n', 'd at his streaky \n', 'glasses, I wanted\n', ' to leave him. An\n', 'd before that? He\n', ' stole those cher\n', 'ries for me at mi\n', 'dnight. We were w\n', 'alking in the rai\n', 'n and I loved him\n', '. And before that\n', '? I saw him comin\n', 'g toward me that \n', 'time at the picni\n'])

Почему-то не получился переворот строки дополненный \x0b символами - он и близко не похож! Я наверное не так понял условия задания (плохо с переводом), или неправильно делаю поворот на 90 градусов.

Вот ещё пример из задания:

data2 = ("Some say the world will end in fire, Some say in ice. From what I've tasted of desire "
         "I hold with those who favor fire. But if it had to perish twice, I think I know enough of hate"
         " To say that for destruction ice Is also great And would suffice.")


data2Sol = ("fa  h ttrheI ilS\nitifakw   s'irdo\nc cotnihftivce m\neAereocaihree,we\n.n   wedroe . i \n\x0bdIdT , es t Sls\n"
"\x0b seoe t.eIaFola\n"
"\x0bw s nIo   srm y\n\x0boatso  Bwhtoee \n\x0bulrautpuhoem nt\n\x0blsuyghetold sdh\n\x0bdoc hir  d wa e\n\x0b  tt niif ohyi \n"
"\x0bsgihoksfawfa nw\n\x0buroaf h vi ti o\n\x0bfent I iotd nfr")

Ответы (1 шт):

Автор решения: MBo

Приведу простое решение, чтобы было понятнее, что требуется.

a = ['What do you remem',
     'ber? When I looke',
     'd at his streaky ',
     'glasses, I wanted',
     ' to leave him. An',
     'd before that? He',
     ' stole those cher',
     'ries for me at mi',
     'dnight. We were w',
     'alking in the rai',
     'n and I loved him',
     '. And before that',
     '? I saw him comin',
     'g toward me that ',
     'time at the picni',
     'c, edgy, foreign.',
     '_________________']

rot = []

for i in range(17):
    s = ''
    for j in reversed(range(17)):
        s += a[j][i]
    rot.append(s)
f = '\n'.join(rot)
print(f)

_ctg?.nadr d gdbW
_,i    lnis tl eh
_ mtIAakietboaara
_eeo nnigsoe st?t
_d wsddnh lfls   
_gaaa  gtfeoeehWd
_ytrwbI .o rasiho
_, d e i rtev,se 
_ t hflnW h e  ny
_fhmioo emot Is o
_oeemrvt eshh tIu
_r   eehw eaiwr  
_eptc deea tmaelr
_iihot  rtc?.naoe
_gcamhhre h  tkom
_nntiaia meHAeyke
_.i ntmiwirend em
→ Ссылка