Week 14

Quiz

  1. How would you open a text file so that you can modify it in Python?

  2. What is the purpose of the character \n?

  3. How do you decrypt a message that has been encrypted using a shift-5 cipher?

  4. What do you need to do in order to decrypt a message when you don't know the encryption key?

Answers:

1.

In [ ]:
f=open(filename,'w')

f.close()
In [ ]:
with open(filename,'w') as f:
  1. Makes a new line in the file.
  1. Loop through each character, find the index in alphabet, subtract 5, graph the new character from alphabet. Encrypt again using a shift of -5.
  1. Decrypt using all possible keys. Then check each message by counting the number of words that appear in the dictionary. The percentage of words should be above a given threshhold, e.g. 75%.

Notes

In [6]:
key = 3
message = 'LeImo tru,  ufh#k ayrae#'
mlist = list(message)
print(mlist)
['L', 'e', 'I', 'm', 'o', ' ', 't', 'r', 'u', ',', ' ', ' ', 'u', 'f', 'h', '#', 'k', ' ', 'a', 'y', 'r', 'a', 'e', '#']
In [7]:
import numpy as np
In [8]:
marr = np.array(mlist)
marr
Out[8]:
array(['L', 'e', 'I', 'm', 'o', ' ', 't', 'r', 'u', ',', ' ', ' ', 'u',
       'f', 'h', '#', 'k', ' ', 'a', 'y', 'r', 'a', 'e', '#'], dtype='<U1')
In [9]:
marr = np.reshape(marr,(3,8))
marr
Out[9]:
array([['L', 'e', 'I', 'm', 'o', ' ', 't', 'r'],
       ['u', ',', ' ', ' ', 'u', 'f', 'h', '#'],
       ['k', ' ', 'a', 'y', 'r', 'a', 'e', '#']], dtype='<U1')
In [15]:
message = 'LeImo tru,  ufhk ayrae'
mlist = list(message)
mlist.insert(-9,'#')
print(mlist)
['L', 'e', 'I', 'm', 'o', ' ', 't', 'r', 'u', ',', ' ', ' ', 'u', '#', 'f', 'h', 'k', ' ', 'a', 'y', 'r', 'a', 'e']
In [14]:
message[:-9] + '&' + message[-9:]
Out[14]:
'LeImo tru,  u&fhk ayrae'
In [ ]: