Advertisement
furas

Python - Transposition cipher

Aug 26th, 2016
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. #
  2. # https://www.facebook.com/groups/learnpython.org/permalink/1175691462495469/
  3. #
  4. # https://en.wikipedia.org/wiki/Transposition_cipher
  5. #
  6.  
  7. import math # import at top of code to show users what modules they need to run it.
  8.  
  9.  
  10. def transencrypt(word, key):
  11.    
  12.     result = ''
  13.    
  14.     length = len(word)
  15.    
  16.     for count1 in range(key):
  17.         for count2 in range(count1, length, key):
  18.             result += word[count2]
  19.  
  20.     return result
  21.  
  22.  
  23. def transdecrypt(word, key):
  24.  
  25.     length = len(word)
  26.  
  27.     result = [''] * length
  28.  
  29.     pos = 0
  30.  
  31.     for count1 in range(key):
  32.         for count2 in range(count1, length, key):
  33.             result[count2] = word[pos]
  34.             pos += 1
  35.  
  36.     return ''.join(result)
  37.  
  38. # encryption - almost identical to decryption - only one line is different
  39.  
  40. def transencrypt(word, key):
  41.    
  42.     length = len(word)
  43.    
  44.     result = [''] * length
  45.  
  46.     pos = 0
  47.    
  48.     for count1 in range(key):
  49.         for count2 in range(count1, length, key):
  50.             result[pos] = word[count2]  # different line
  51.             pos += 1
  52.  
  53.     return ''.join(result)
  54.  
  55.  
  56. # encryption - version with iterator
  57.  
  58. def transdecrypt_version2(word, key):
  59.  
  60.     length = len(word)
  61.  
  62.     result = [''] * length
  63.  
  64.     letter = iter(word) # iterator let you get next element/letter using next()
  65.    
  66.     for count1 in range(key):
  67.         for count2 in range(count1, length, key):
  68.             result[count2] = next(letter)
  69.  
  70.     return ''.join(result)
  71.  
  72.  
  73. # --- almost "UnitTest" ;) ---
  74.  
  75. print('--- encryption ---')
  76.  
  77. print(transencrypt('', 5) == '')
  78. print(transencrypt('bye', 5) == 'bye')
  79. print(transencrypt('hello', 5) == 'hello')
  80.  
  81. print(transencrypt('hello world', 5) == 'h dewlolrol')
  82.  
  83. print('--- decryption ---')
  84.  
  85. print(transdecrypt('', 5) == '')
  86. print(transdecrypt('bye', 5) == 'bye')
  87. print(transdecrypt('hello', 5) == 'hello')
  88.  
  89. print(transdecrypt('h dewlolrol', 5) == 'hello world')
  90.  
  91. # --- or using `asssert` command ---
  92.  
  93. assert transencrypt('hello world', 5) == 'h dewlolrol', 'wrong encryption'
  94. assert transdecrypt('h dewlolrol', 5) == 'hello world', 'wrong decryption'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement