Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # https://www.facebook.com/groups/learnpython.org/permalink/1175691462495469/
- #
- # https://en.wikipedia.org/wiki/Transposition_cipher
- #
- import math # import at top of code to show users what modules they need to run it.
- def transencrypt(word, key):
- result = ''
- length = len(word)
- for count1 in range(key):
- for count2 in range(count1, length, key):
- result += word[count2]
- return result
- def transdecrypt(word, key):
- length = len(word)
- result = [''] * length
- pos = 0
- for count1 in range(key):
- for count2 in range(count1, length, key):
- result[count2] = word[pos]
- pos += 1
- return ''.join(result)
- # encryption - almost identical to decryption - only one line is different
- def transencrypt(word, key):
- length = len(word)
- result = [''] * length
- pos = 0
- for count1 in range(key):
- for count2 in range(count1, length, key):
- result[pos] = word[count2] # different line
- pos += 1
- return ''.join(result)
- # encryption - version with iterator
- def transdecrypt_version2(word, key):
- length = len(word)
- result = [''] * length
- letter = iter(word) # iterator let you get next element/letter using next()
- for count1 in range(key):
- for count2 in range(count1, length, key):
- result[count2] = next(letter)
- return ''.join(result)
- # --- almost "UnitTest" ;) ---
- print('--- encryption ---')
- print(transencrypt('', 5) == '')
- print(transencrypt('bye', 5) == 'bye')
- print(transencrypt('hello', 5) == 'hello')
- print(transencrypt('hello world', 5) == 'h dewlolrol')
- print('--- decryption ---')
- print(transdecrypt('', 5) == '')
- print(transdecrypt('bye', 5) == 'bye')
- print(transdecrypt('hello', 5) == 'hello')
- print(transdecrypt('h dewlolrol', 5) == 'hello world')
- # --- or using `asssert` command ---
- assert transencrypt('hello world', 5) == 'h dewlolrol', 'wrong encryption'
- assert transdecrypt('h dewlolrol', 5) == 'hello world', 'wrong decryption'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement