code = {'A': 0, 'B': 1,'C': 2,'D': 3, 'E': 4,'F': 5,'G': 6,'H': 7, 'I': 8,'J': 9,'K': 10,'L': 11, 'M': 12,'N': 13,'O': 14,'P': 15, 'Q': 16,'R': 17,'S': 18,'T': 19, 'U': 20,'V': 21,'W': 22, 'X': 23, 'Y': 24,'Z': 25} reverse_code = dict((v,k) for k, v in code.iteritems()) #specify reverse- #associated dictionary def encoder(message, key_word): list_of_message = [] key = [] encoded_message = [] for a in message:#convert string of letters to list of associated numbers if a in code: list_of_message.append(code[a]) else: list_of_message.append(a) while len(key) < len(list_of_message):#create the key to encode the message for a in key_word: key.append(code[a]) key = key[0:len(list_of_message)]#set length of key equal to length of messsage for a,b in zip(key, list_of_message):#create encoded message if b not in range(0,26): encoded_message.append(b)#transfer non-encoded elements else: #encolde elements c = b + a if c > 25:#this is quivalent to looping the dictionary. c = c - 25 encoded_message.append(reverse_code[c])#use reverse dictionary to #convert back into letters encoded_message = ''.join(encoded_message)#convert encoded message to string print "encoded message:", encoded_message return encoded_message def decoder(encoded_message, key_word): decoded_list = [] key = [] message = [] for a in encoded_message: if a in code: decoded_list.append(code[a]) else: decoded_list.append(a) while len(key) < len(decoded_list): for a in key_word: key.append(code[a]) key = key[0:len(decoded_list)] for a,b in zip(key, decoded_list): if b not in range(0,26): message.append(b) else: c = b - a if c < 0: c += 25 message.append(reverse_code[c]) message = ''.join(message) print 'decoded message:', message return message def encode_or_decode(): encode_decode = raw_input("do you want to encode or decode? ") #.ascii_lowercase message = raw_input("Enter message: ")#.ascii_uppercase key_word = raw_input("Enter key: ")#.ascii_uppercase if encode_decode == "encode": encoder(message, key_word) if encode_decode == "decode": decoder(message, key_word) encode_or_decode()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question