Skip to content
Newer
Older
100644 55 lines (40 sloc) 1.74 KB
f16b361 @asweigart Initial commit.
authored Aug 19, 2012
1 # Transposition Cipher Decryption
2 # http://inventwithpython.com/codebreaker (BSD Licensed)
3
4 import math, pyperclip
5
6 def main():
7 myMessage = 'Cenoonommstmme oo snnio. s s c'
8 myKey = 8
9
10 translated = decryptMessage(myKey, myMessage)
11
91f8abb @asweigart First round of personal fixes. This is an unhelpful log message.
authored Aug 24, 2012
12 # Print with a | (called "pipe" character) after it in case
13 # there are spaces at the end of the decrypted message.
f16b361 @asweigart Initial commit.
authored Aug 20, 2012
14 print(translated + '|')
15
16 pyperclip.copy(translated)
17
18
19 def decryptMessage(key, message):
20 # The transposition decrypt function will simulate the "columns" and
21 # "rows" of the grid that the plaintext is written on by using a Python
22 # list of strings. First, we need to calculate a few values.
23
24 # The number of "columns" our transposition grid:
25 numOfColumns = math.ceil(len(message) / key)
26 # The number of "rows" our grid will need:
27 numOfRows = key
28 # The number of "shaded boxes" in the last "column" of the grid:
29 numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
30
31 # Each string in plaintext represents a column in the transposition grid.
32 plaintext = [''] * numOfColumns
33
34 # The col and row variables point to where in the grid the next character
35 # in the encrypted message will go.
36 col = 0
37 row = 0
38
39 for i in range(len(message)):
40 plaintext[col] += message[i]
41 col += 1 # point to next column
42
43 # If there are no more columns OR we're at a shaded box, go back to
44 # the first column and the next row.
45 if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
46 col = 0
47 row += 1
48
49 return ''.join(plaintext)
50
91f8abb @asweigart First round of personal fixes. This is an unhelpful log message.
authored Aug 25, 2012
51
f16b361 @asweigart Initial commit.
authored Aug 20, 2012
52 # If transpositionDecrypt.py is run (instead of imported as a module) call
53 # the main() function.
54 if __name__ == '__main__':
91f8abb @asweigart First round of personal fixes. This is an unhelpful log message.
authored Aug 25, 2012
55 main()
Something went wrong with that request. Please try again.