Question

In: Computer Science

WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU! In this programming assignment, you...

WE ARE USING PYTHON TO COMPLETE THIS ASSIGNMENT :) THANK YOU!

In this programming assignment, you will write functions to encrypt and decrypt messages using simple substitution ciphers. Your solution MUST include:

  • a function called encode that takes two parameters:
    • key, a 26-character long string that identifies the ciphertext mapping for each letter of the alphabet, in order;
    • plaintext, a string of unspecified length that represents the message to be encoded.

    encode will return a string representing the ciphertext.

  • a function called decode that takes two parameters:
    • key, a 26-character long string that identifies the ciphertext mapping for each letter of the alphabet, in order;
    • ciphertext, a string of unspecified length that represents the message to be decoded.

    decode will return a string representing the plaintext.

Copy and paste the following statements into your file as the first two statements of your main program. These lines represent Python lists of messages for you to encode and decode to test the functions you write.

    plaintextMessages = [
        ["This is the plaintext message.",
         "bcdefghijklmnopqrstuvwxyza"],
        ["Let the Wookiee win!",
         "epqomxuagrdwkhnftjizlcbvys"],
        ["Baseball is 90% mental. The other half is physical.\n\t\t- Yogi Berra",
         "hnftjizlcbvysepqomxuagrdwk"],
        ["I used to think I was indecisive, but now I'm not too sure.",
         "mqncdaigyhkxflujzervptobws"],
        ["Einstein's equation 'e = mc squared' shows that mass and\n\t\tenergy are interchangeable.",
         "bludcmhojaifxrkzenpsgqtywv"] ]

    codedMessages = [
        ["Uijt jt uif dpefe nfttbhf.",
         "bcdefghijklmnopqrstuvwxyza"],
        ["Qnhxgomhqm gi 10% bnjd eho 90% omwlignh. - Zghe Xmy",
         "epqomxuagrdwkhnftjizlcbvys"],
        ["Ulj njxu htgcfj C'gj jgjm mjfjcgjt cx, 'Ep pej jyxj veprx rlhu\n\t\t uljw'mj tpcez jculjm'. - Mcfvw Zjmghcx",
         "hnftjizlcbvysepqomxuagrdwk"],
        ["M 2-wdme uxc yr kylc ua xykd m qxdlcde, qpv wup cul'v gmtd mlw\n\t\t vuj aue yv. - Hdeew Rdyladxc",
         "mqncdaigyhkxflujzervptobws"] ]

You may alter the spacing or indentation of the two lines to conform to the rest of your code, but you are not allowed to change the strings or structure of the lists.

plaintextMessages is a list consisting of five items. Each item is a list of two strings corresponding to a plaintext message and a key. For each of these five items, you should:

  • print the plaintext message.
  • encode the message and print the ciphertext.
  • decode the ciphertext message you just calculated and print the plaintext message again. The purpose of this is to demonstrate that your encode and decode functions work properly as inverses of each other.

If you have done this correctly, the output from your program for the first data item should look like the following:

plaintext:   This is the plaintext message.
encoded:     Uijt jt uif qmbjoufyu nfttbhf.
re-decoded:  This is the plaintext message.

Then print a blank line to separate this block of three lines from the next block.

codedMessages is a list consisting of four items. Each item is a list of two strings corresponding to a ciphertext message and a key. For each of these four items, you should:

  • print the ciphertext message.
  • decode the message and print the ciphertext.

If you have done this correctly, the output from your program for the first data item should look like the following:

encoded:  Uijt jt uif dpefe nfttbhf.
decoded:  

Then print a blank line to separate this block of two lines from the next block.

Special notes:

  • Encrypted and decrypted lower-case letters should map to lower-case letters, as defined by the key.
  • Encrypted and decrypted upper-case letters should map to upper-case letters. Note that upper-case letters do not appear in the key! (Look at the first character in the expected output shown above: the upper-case "T" maps to an upper-case "U" in the encoded message.) Your program must detect when an upper-case letter appears in the data, and figure out how to convert it to the correct upper-case letter based on the corresponding lower-case letters in the key.
  • Non-alphabetic characters, such as numbers, spaces, tabs, punctuation, etc. should not be changed by either encode() or decode().

Solutions

Expert Solution

Given below is the code for the question. PLEASE MAKE SURE INDENTATION IS EXACTLY AS SHOWN IN IMAGE.
Please do rate the answer if it helped. Thank you.

def encode(key, plaintext):
   ciphertext = ''
   for c in plaintext:
       if c >= 'A' and c <= 'Z':
           idx = ord(c) - ord('A')
           c = key[idx]
           #change to upper case
           c = chr(ord(c) - ord('a') + ord('A'))
       elif c >= 'a' and c <= 'z':
           idx = ord(c) - ord('a')
           c = key[idx]
       ciphertext = ciphertext + c
   return ciphertext

def decode(key, ciphertext):
   plaintext = ''
   for c in ciphertext:
       if c.isalpha():
           idx = key.index(c.lower())
           if c >= 'A' and c <= 'Z':
               c = chr(ord('A') + idx)
           elif c >= 'a' and c <= 'z':
               c = chr(ord('a') + idx)
       plaintext = plaintext + c
   return plaintext

def main():
   plaintextMessages = [
       ["This is the plaintext message.",
       "bcdefghijklmnopqrstuvwxyza"],
       ["Let the Wookiee win!",
       "epqomxuagrdwkhnftjizlcbvys"],
       ["Baseball is 90% mental. The other half is physical.\n\t\t- Yogi Berra",
       "hnftjizlcbvysepqomxuagrdwk"],
       ["I used to think I was indecisive, but now I'm not too sure.",
       "mqncdaigyhkxflujzervptobws"],
       ["Einstein's equation 'e = mc squared' shows that mass and\n\   t\tenergy are interchangeable.",
       "bludcmhojaifxrkzenpsgqtywv"] ]

   codedMessages = [
       ["Uijt jt uif dpefe nfttbhf.",
       "bcdefghijklmnopqrstuvwxyza"],
       ["Qnhxgomhqm gi 10% bnjd eho 90% omwlignh. - Zghe Xmy",
       "epqomxuagrdwkhnftjizlcbvys"],
       ["Ulj njxu htgcfj C'gj jgjm mjfjcgjt cx, 'Ep pej jyxj veprx rlhu\n\t\t uljw'mj tpcez jculjm'. - Mcfvw Zjmghcx",
       "hnftjizlcbvysepqomxuagrdwk"],
       ["M 2-wdme uxc yr kylc ua xykd m qxdlcde, qpv wup cul'v gmtd mlw\n\t\t vuj aue yv. - Hdeew Rdyladxc",
       "mqncdaigyhkxflujzervptobws"] ]
         
   for i in range(len(plaintextMessages)):
       plaintext = plaintextMessages[i][0]
       key = plaintextMessages[i][1]
       ciphertext = encode(key, plaintext);
       print('plaintext:', plaintext)
       print('encoded:', ciphertext)
       print('re-decoded:', decode(key, ciphertext))
       print()


   for i in range(len(codedMessages)):
       ciphertext = codedMessages[i][0]
       key = codedMessages[i][1]
       plaintext = decode(key, ciphertext);
       print('encoded:', ciphertext)
       print('decoded:', plaintext)
       print()
          
if __name__ == "__main__":
   main()


output
----
plaintext: This is the plaintext message.
encoded: Uijt jt uif qmbjoufyu nfttbhf.
re-decoded: This is the plaintext message.

plaintext: Let the Wookiee win!
encoded: Wmz zam Bnndgmm bgh!
re-decoded: Let the Wookiee win!

plaintext: Baseball is 90% mental. The other half is physical.
- Yogi Berra
encoded: Nhxjnhyy cx 90% sjeuhy. Ulj puljm lhyi cx qlwxcfhy.
- Wpzc Njmmh
re-decoded: Baseball is 90% mental. The other half is physical.
- Yogi Berra

plaintext: I used to think I was indecisive, but now I'm not too sure.
encoded: Y prdc vu vgylk Y omr ylcdnyrytd, qpv luo Y'f luv vuu rped.
re-decoded: I used to think I was indecisive, but now I'm not too sure.

plaintext: Einstein's equation 'e = mc squared' shows that mass and
\ t energy are interchangeable.
encoded: Cjrpscjr'p cegbsjkr 'c = xu pegbncd' poktp sobs xbpp brd
\ s crcnhw bnc jrscnuobrhcblfc.
re-decoded: Einstein's equation 'e = mc squared' shows that mass and
\ t energy are interchangeable.

encoded: Uijt jt uif dpefe nfttbhf.
decoded: This is the coded message.

encoded: Qnhxgomhqm gi 10% bnjd eho 90% omwlignh. - Zghe Xmy
decoded: Confidence is 10% work and 90% delusion. - Tina Fey

encoded: Ulj njxu htgcfj C'gj jgjm mjfjcgjt cx, 'Ep pej jyxj veprx rlhu
uljw'mj tpcez jculjm'. - Mcfvw Zjmghcx
decoded: The best advice I've ever received is, 'No one else knows what
they're doing either'. - Ricky Gervais

encoded: M 2-wdme uxc yr kylc ua xykd m qxdlcde, qpv wup cul'v gmtd mlw
vuj aue yv. - Hdeew Rdyladxc
decoded: A 2-year old is kind of like a blender, but you don't have any
top for it. - Jerry Seinfeld


Related Solutions

In Python For this programming assignment, we are going to investigate how much "work" different sorting...
In Python For this programming assignment, we are going to investigate how much "work" different sorting routines do, based on the input size and order of the data. We will record the work done by writing output CSV (comma separated value) files and creating various plots using matplotlib. Note: for this assignment, do not use Jupyter Notebook to code your solution. Use standard .py files and save your output to .csv and .png files (see the program details below for...
please give complete code in python using def function thank you! Validate Credit Card Numbers Credit...
please give complete code in python using def function thank you! Validate Credit Card Numbers Credit card numbers can be quickly validated by the Luhn checksum algorithm. Start at the rightmost digit save one (the last being the checksum digit). Moving left, double the value of every second digit. If the doubled value is greater than nine, then subtract 9 from the doubled value to renormalize within the range 0–9. Sum all the digits including the checksum digit. If this...
Complete the 3 programming problems in this assignment by using Microsoft Visual Studio Suite. Compile your...
Complete the 3 programming problems in this assignment by using Microsoft Visual Studio Suite. Compile your solutions for each problem solved in a Word or Google document which includes (a) the pseudocode, (b) the C# codes and (c) the execution result (screen capture just the answer part using Snipping Tool, avoiding non-related or blank spaces). Notice for readability, that the (a) & (b) are in text mode and the (c) is in image mode. Use proper titles and wording in...
Complete the 3 programming problems in this assignment by using Microsoft Visual Studio Suite. Compile your...
Complete the 3 programming problems in this assignment by using Microsoft Visual Studio Suite. Compile your solutions for each problem solved in a Word or Google document which includes (a) the pseudocode, (b) the C# codes and (c) the execution result (screen capture just the answer part using Snipping Tool, avoiding non-related or blank spaces). Notice for readability, that the (a) & (b) are in text mode and the (c) is in image mode. Use proper titles and wording in...
Complete this programming problem in this assignment by using Microsoft Visual Studio Suite. Compile your solutions...
Complete this programming problem in this assignment by using Microsoft Visual Studio Suite. Compile your solutions for each problem solved in a Word or Google document which includes (a) the pseudocode, (b) the C# codes and (c) the execution result (screen capture just the answer part using Snipping Tool, avoiding non-related or blank spaces). Notice for readability, that the (a) & (b) are in text mode and the (c) is in image mode. Use proper titles and wording in the...
Using Python In this assignment we will try to add tuples, lists, if statements and strings...
Using Python In this assignment we will try to add tuples, lists, if statements and strings to our program. For example, you can ask for a user for a couple items, their name and age – and depending on their age, print out a predefined list. You could ask for some string input and decide to do something with the output. You could ask for three items, 1) age, 2) are you a male or female and 3) are your...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a...
USING PYTHON. Thank you in advance Write a program that allows the user to enter a series of string values into a list. When the user enters the string ‘done’, stop prompting for values. Once the user is done entering strings, create a new list containing a palindrome by combining the original list with the content of the original list in a reversed order. Sample interaction: Enter string: My Enter string: name Enter string: is Enter string: Sue Enter string:...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the...
Programming Language: JAVA In this assignment you will be sorting an array of numbers using the bubble sort algorithm. You must be able to sort both integers and doubles, and to do this you must overload a method. Bubble sort work by repeatedly going over the array, and when 2 numbers are found to be out of order, you swap those two numbers. This can be done by looping until there are no more swaps being made, or using a...
Python Programming This assignment will give you practice with interactive programs, if/else statements, collections, loops and...
Python Programming This assignment will give you practice with interactive programs, if/else statements, collections, loops and functions. Problem Description A small car yard dealing in second hand cars needs an application to keep records of cars in stock. Details of each car shall include registration(rego), model, color, price paid for the car (i.e. purchase price) and selling price. Selling price is calculated as purchased price plus mark-up of 30%. For example, Toyota Corolla bought for $20,000 will have the selling...
1. INTRODUCTION The goal of this programming assignment is for students to write a Python program...
1. INTRODUCTION The goal of this programming assignment is for students to write a Python program that uses repetition (i.e. “loops”) and decision structures to solve a problem. 2. PROBLEM DEFINITION  Write a Python program that performs simple math operations. It will present the user with a menu and prompt the user for an option to be selected, such as: (1) addition (2) subtraction (3) multiplication (4) division (5) quit Please select an option (1 – 5) from the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT