Skip to content
Newer
Older
100644 57 lines (42 sloc) 1.87 KB
f16b361 @asweigart Initial commit.
authored
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
12 # Print the (decrypted) string in translated to the screen, with
13 # a | (called "pipe" character) after it in case there are spaces at the
14 # end of the decrypted message.
15 print(translated + '|')
16
17 # Copy the (decrypted) string in translated to the clipboard.
18 pyperclip.copy(translated)
19
20
21 def decryptMessage(key, message):
22 # The transposition decrypt function will simulate the "columns" and
23 # "rows" of the grid that the plaintext is written on by using a Python
24 # list of strings. First, we need to calculate a few values.
25
26 # The number of "columns" our transposition grid:
27 numOfColumns = math.ceil(len(message) / key)
28 # The number of "rows" our grid will need:
29 numOfRows = key
30 # The number of "shaded boxes" in the last "column" of the grid:
31 numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
32
33 # Each string in plaintext represents a column in the transposition grid.
34 plaintext = [''] * numOfColumns
35
36 # The col and row variables point to where in the grid the next character
37 # in the encrypted message will go.
38 col = 0
39 row = 0
40
41 for i in range(len(message)):
42 plaintext[col] += message[i]
43 col += 1 # point to next column
44
45 # If there are no more columns OR we're at a shaded box, go back to
46 # the first column and the next row.
47 if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
48 col = 0
49 row += 1
50
51 return ''.join(plaintext)
52
53 # If transpositionDecrypt.py is run (instead of imported as a module) call
54 # the main() function.
55 if __name__ == '__main__':
56 main()
Something went wrong with that request. Please try again.