Encrypting a columnar transposition cipher

I'm trying to figure out how to encrypt a columnar transposition cipher in Python given a plaintext uppercase string and a number key of any length. For example, if the key is 3124 and the string is 'IHAVETWOCATS', it would organize the string like so:


and then return the characters in column 1 first, then column 2, etc, until finally returning the encrypted string 'HTAAWTIECVOS'. So far I know that I'll need to use an accumulator, and I've been toying with the idea of using a dictionary, but I'm just completely stuck. These are some of the functions I've tried:

def columnar(plaintext,key): cipher='' acc=0 for i in range(len(key)): while acc<(len(plaintext)/len(key)): cipher=cipher+plaintext[i+acc*5] acc=acc+1 return(cipher)

^This only returns a few letters, not a string of appropriate length.

def columnar(plaintext,key) values={} seqlist=[] nextvalue=1 indices=rand(len(key)) for letter in plaintext: for i in indices: if letter==key[i]: values[i]=nextvalue nextvalue=nextvalue+1 for i in indices: seqlist.append(values[i]) return seqlist

^The above function returns a KeyError: 0 error. Thank you very much for any help!


def split_len(seq, length): return [seq[i:i + length] for i in range(0, len(seq), length)] def encode(key, plaintext): order = { int(val): num for num, val in enumerate(key) } ciphertext = '' for index in sorted(order.keys()): for part in split_len(plaintext, len(key)): try: ciphertext += part[order[index]] except IndexError: continue return ciphertext print(encode('3214', 'IHAVETWOCATS')) #>>> HTAAWTIECVOS

split_len is by Ian Bicking

So i split the code into chunks with split_len then use dictionary comprehension to just get correct order of indexes and finally i concatanate the letters in that order.


def encode(txt,key): sz = len(key) # how big are the columns cols = list(map("".join,zip(*zip(*[iter(txt)]*sz)))) # list partitioned into columns return "".join([cols[key.index(str(c))] for c in range(1,sz+1)]) encoded = encode("IHAVETWOCATS","3124") print encoded

is probably how I would do it


  • How to get the content of a Label within a Grid
  • How to parse single file using Python bindings to Clang?
  • Dynamically loading jar from arbitrary url
  • Customizing ASP.NET Membership Provider to add logging capabilities
  • How can I perform operations in JavaScript just like we do pipeline of operations in Java streams?
  • C++ - using glfwGetTime() for a fixed time step
  • How to calculate a sum of sequence of numbers in Prolog
  • F#: Recursive Functions: Concatenating the common values between two lists
  • Write a function that calculate the sum of integers in a list in Erlang
  • How to access list of email accounts with cPanel API?
  • File Not Found Error in Python
  • Unknown C# type
  • What is the first step to using a REST API in Rails?
  • Insert space after period using sed
  • How to replace TouchesBegan with UIGestureRecognizer
  • How can I count unique terms in a plaintext file case-insensitively?
  • Programmatically Update Linked Named Range of excel object in MS Word (2007)
  • How to change placeholder text in an autocomplete activity of android google place?
  • What's the name of this finding square root algorithm?
  • Python PIL to extract number from image
  • Cast between interfaces whose interface signatures are same
  • Excel's Macro-Recorder usage
  • Grails calculated field in SQL
  • Remove final comma from string in vb.net
  • copying resource to sdcard gives a damaged file in android
  • QLineEdit password safety
  • Read text file and split every line in MSBuild
  • C# - Serializing and deserializing static member
  • How to add date and time under each post in guestbook in google app engine
  • Java applet as stand-alone Windows application?
  • output of program is not same as passed argument
  • Does CUDA 5 support STL or THRUST inside the device code?
  • How to handle AllServersUnavailable Exception
  • JSON with duplicate key names losing information when parsed
  • Statically linking a C++ library to a C# process using CLI or any other way
  • VBA Convert delimiter text file to Excel
  • Why winpcap requires both .lib and .dll to run?
  • Return words with double consecutive letters
  • Error creating VM instance in Google Compute Engine
  • Reading document lines to the user (python)