WHERE THE DREAM STARTS 2
Challenge
Musicians transpose keys regularly. Cryptanalysts transpose columns regularly.
Keylength: key of cipher in Where the dream starts 1
Keyword: ascii_lowercase[:keylength]
File given: output.txt
Understanding the cipher
Literally handed to you. Transposition cipher, keylength is the key of the last cipher (the Caesar shift from part 1, which was 3), and the keyword is ascii_lowercase[:keylength], so just "abc". That's a columnar transposition with a known column count and an already-sorted column order.
Solution
from string import ascii_lowercase
ct = "T aiglhTtn0-t-yf-4}hfgsaitFrss2hk--fteel sgC{4p3-330gl!o"
keylength = 3
keyword = ascii_lowercase[:keylength]
def cosa(ct, keyword):
ncols = len(keyword)
nrows = -(-len(ct) // ncols)
nfull = len(ct) - ncols * (nrows - 1)
order = sorted(range(ncols), key=lambda i: (keyword[i], i))
col_len = [nrows if i < nfull else nrows - 1 for i in range(ncols)]
cols = [None] * ncols
pos = 0
for col_idx in order:
length = col_len[col_idx]
cols[col_idx] = ct[pos : pos + length]
pos += length
rows = []
for r in range(nrows):
row = "".join(cols[c][r] if r < len(cols[c]) else "" for c in range(ncols))
rows.append(row)
return "".join(rows)
print(cosa(ct, keyword))