Problem 204333 · medium · Level 02 Linear Data Structures

Unwinding the Scytale

py-slicing · strings · slice assignment

An old way to hide a message: write it in rows of width characters (the last row may be shorter), then copy it out column by column, top to bottom, left to right. With width = 5:

M E E T A
T D A W N
B Y T H E
G A T E

Reading the columns gives "MTBG" + "EDYA" + "EATT" + "TWHE" + "ANE", so the hidden text is "MTBGEDYAEATTTWHEANE".

Write unwind(cipher, width) that takes a hidden text made this way and returns the original message.

Examples

Input:  cipher = "MTBGEDYAEATTTWHEANE", width = 5
Output: "MEETATDAWNBYTHEGATE"

Input:  cipher = "HLODEORLWL", width = 3
Output: "HELLOWORLD"
Explanation: The rows were HEL / LOW / ORL / D, so the columns are HLOD, EOR and LWL.

Input:  cipher = "abc", width = 10
Output: "abc"
Explanation: The message fits in one row, so every column holds one character.

The setup defines wind(text, width), which hides a message this way, so you can try your function with unwind(wind("some text", 4), 4).

Constraints

  • 0 <= len(cipher) <= 10**5
  • 1 <= width <= 10**5
  • cipher may contain any characters, including spaces.

Goals

  • Read every k-th character of a string with a stepped slice
  • Work out how long each column is when the last row is short
  • Fill every k-th position of a list at once with slice assignment
Starting Python…