Question

In: Computer Science

Using Python 3 The primary objective of this assignment is to reinforce the concepts of string...

Using Python 3

The primary objective of this assignment is to reinforce the concepts of string processing.

Part A: Even or Odd

For this first part, write a function that will generate a random number within some range (say, 1 to 50), then prompt the user to answer if the number is even or odd. The user will then input a response and a message will be printed indicated whether it was correct or not. This process should be repeated 5 times, using a new random number for each play, regardless of whether the user was correct or not.

Notes

  • A correct response for an even number can be any of the following: “even”, “Even”, “EVEN”, “e”, “E”. “EiEiO”. The main criterion is that a correct response begins with the letter “e”, regardless of case. The same goes for an odd number – a correct response should begin with the letter “o”.
  • If the user enters an invalid response, they should be notified. However, an invalid response still counts as one of the 5 plays.
  • The solution should contain a loop (for or while) and a few if statements. An example execution is shown below:

>>> assign2PartA()
Is 41 odd or even? Odd
   Correct
Is 48 odd or even? Even
   Correct
Is 3 odd or even? e
   Incorrect
Is 20 odd or even? o
   Incorrect
Is 42 odd or even? xyz
   You did not enter a correct reply.
     Please answer using Odd or Even

Part B: Vowel Counting

The second task is to write a function that counts, and prints, the number of occurrences for each vowel (a, e, i, o and u) in a given phrase and outputs a (new) phrase with the vowels removed. The phrase should be accepted as a parameter to the function. If the (original) phrase is empty, you should output an appropriate error message, and obviously with no vowel counts. If the phrase contains no vowels, a message should be displayed, and the count can be omitted – since there is no point in displaying 0 for each vowel! A message should also be displayed if the phrase contains only vowels, but the counts should still be displayed.

Notes

  • Recall that you can use the tab escape character (“\t”) for spacing to align the text, or use a given width in the f-string (print(f"{count_a:4}, ……”), where the value of count_a here is right justified in 4 columns.)
  • Be sure to correctly handle both upper- and lower-case letters (e.g. both “a” and “A” should be counted as an instance of the letter “A”.) The new phrase (with vowels removed) should preserve the letter cases from the original phrase. Be sure to show output for all possible scenarios in your submitted output. A few example executions are shown below. In the first example, the escape sequence \" allows for inclusion of a " within a string delimited by two ", see slide 9 in “Working with Strings.”

>>> assign2PartB("Remember that context here defines \"+\" as 'Concatenate'")
   A    E    I    O    U
   4   10    1    2    0

The original phrase is: Remember that context here defines "+" as 'Concatenate'
The phrase without vowels is: Rmmbr tht cntxt hr dfns "+" s 'Cnctnt'

>>> assign2PartB("bcdfghjklmnpqrstvwxyz")

The phrase contains no vowels: bcdfghjklmnpqrstvwxyz

>>> assign2PartB("aeiouAEIOU")
   A    E    I    O    U
   2    2    2    2    2

The phrase contains only vowels: aeiouAEIOU

>>> assign2PartB("")

The input phrase is empty!

>>>

Solutions

Expert Solution

** Compiled in Spyder **

CODE:

import random

def assign2PartA():
    # Running a for loop for 5 iterations.
    for i in range(5):
        # Generating a random number between 1 and 50 using random.randint().
        num = random.randint(1, 50)
        # Creating a question by concatenating the random int and string.
        question = 'Is ' + str(num) + ' odd or even? '
        # Reading response from the user.
        response = input(question)
        # Converting the input to upper case, so that we can just check for capital letters.
        response = response.upper()
        # If the first letter is not 'E' or 'O', then it is an invalid input.
        if response[0] != 'E' and response[0] != 'O':
            print('  You did not enter a correct reply.\n   Please answer using Odd or Even')
        # If the random number generated is even and the response starts with 'E', 
        # then the answer is correct.
        elif num % 2 == 0 and response[0] == 'E':
            print('  Correct')
        # If the random number generated is odd and the response starts with 'O', 
        # then the answer is correct.
        elif num % 2 != 0 and response[0] == 'O':
            print('  Correct')
        # else the answer is incorrect.
        else:
            print('  Incorrect')

def assign2PartB(string):
    # Initializing a, e, i, o, u as 0.
    # To store the number of occurrence.
    a = e = i = o = u = 0
    
    # Traversing through the string letter by letter and incrementing the value of the variable
    # corresponding to vowels.
    for letter in string:
        if letter == 'A' or letter == 'a':
            a += 1
        elif letter == 'E' or letter == 'e':
            e += 1
        elif letter == 'I' or letter == 'i':
            i += 1
        elif letter == 'O' or letter == 'o':
            o += 1
        elif letter == 'U' or letter == 'u':
            u += 1
    # total -> total number of vowels present in the string.
    total = (a + e + i + o + u)
    
    # If the string is empty, print 'phrase is empty'.
    if string == "":
        print('The input phrase is empty!')
    # If there is no vowels, print 'no vowels'.
    elif total == 0:
        print('The phrase contains no vowels:', string)
    else:
        # else print the occurrences of each vowels.
        print('A \t E \t I \t O \t U')
        print(a, '\t', e, '\t', i, '\t', o, '\t', u)
        
        # If all the letters are vowels, print 'only vowels'.
        if len(string) == total:
            print('The phrase contains only vowels:', string)
        # else print the original string and another string wihtout vowels.
        else:
            print('The original phrase is:', string)
            # creating an empty string.
            new_string = ""
            # Appending all the consonant to new_string.
            for letter in string:
                if letter not in "aeiouAEIOU":
                    new_string += letter
            
            print('The phrase without vowels is:', new_string)

# calling assign2PartA()
assign2PartA()
print()

# calling assign2PartB() with different strings
string1 = "Remember that context here defines \"+\" as 'Concatenate'"
string2 = "bcdfghjklmnpqrstvwxyz"
string3 = "aeiouAEIOU"
string4 = ""

assign2PartB(string1)
print()
assign2PartB(string2)
print()
assign2PartB(string3)
print()
assign2PartB(string4)

Screenshots:

refer this to know the proper indentations.

Sample I/O:

Hope this Helps:)

Please consider giving this answer a thumbs up.

If this answer didn't satisfies your requirements or needs modifications, please let me know in the comment section before giving a thumbs down.

Thank you! Stay Safe!!!


Related Solutions

The primary objective of this assignment is to reinforce the concepts of string processing. Part A:...
The primary objective of this assignment is to reinforce the concepts of string processing. Part A: Even or Odd [10 marks] For this first part of the assignment, write a function that will generate a random number within some range (say, 1 to 50), then prompt the user to answer if the number is even or odd. The user will then input a response and a message will be printed indicated whether it was correct or not. This process should...
The primary objective of this assignment is to reinforce the concepts of string processing. Part A:...
The primary objective of this assignment is to reinforce the concepts of string processing. Part A: Even or Odd For this first part, write a function that will generate a random number within some range (say, 1 to 50), then prompt the user to answer if the number is even or odd. The user will then input a response and a message will be printed indicated whether it was correct or not. This process should be repeated 5 times, using...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string methods to slice strings, working with dictionaries and using-step wise development to complete your program. Python is an excellent tool for reading text files and parsing (i.e. filtering) the data. Your assignment is to write a Python program in four steps that reads a Linux authentication log file, identifies the user names used in failed password attempts and counts the times each user name...
The purpose of this assignment is to reinforce Ada concepts. Define a Complex-numbers package includes the...
The purpose of this assignment is to reinforce Ada concepts. Define a Complex-numbers package includes the following operations: Addition Subtraction Multiplication Division A “main program” needs to create one or more complex numbers, perform the various arithmetic operations, and then display results. Develop the program in ADA code with several packages. Write a short report that documents all work done, including the overall design, explanation of the implementation, the input data used to run the program, the output of the...
Objective This assignment aims to investigate the concepts in solving problems on the special theory of...
Objective This assignment aims to investigate the concepts in solving problems on the special theory of relativity, analyze the effects of relativity and evaluate the validity of results on the application of relativity. Problem Solving, Analysis and Evaluating of the Validity of Results Direction: Solve the given problem using systematic/logical solution. Make an analysis and evaluation of the results. Rubrics will be used in marking. (1) Determine Ƴ if v = 0.01c; 0.1c; 0.5c; 0.6c; 0.8c; 0.9c; 0.99c; 1.00c; and...
The assignment is to build a program in Python that can take a string as input...
The assignment is to build a program in Python that can take a string as input and produce a “frequency list” of all of the wordsin the string (see the definition of a word below.)  For the purposes of this assignment, the input strings can be assumed not to contain escape characters (\n, \t, …) and to be readable with a single input() statement. When your program ends, it prints the list of words.  In the output, each line contains of a...
Assignment #3 Introduction to C Programming – COP 3223 Objectives To reinforce the use of If-Else...
Assignment #3 Introduction to C Programming – COP 3223 Objectives To reinforce the use of If-Else statements To learn how to use while loops Introduction: Mission to Mars Your friend has been playing a new Mars Colony simulator nonstop! They are always talking about how cool it would be if they could be a on the first real-life mission to Mars! To amuse your friend, you have decided to create a series of programs about the possible first colony on...
For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
This assignment is to give you practice using enums, string variables, and string functions. In order...
This assignment is to give you practice using enums, string variables, and string functions. In order to get full credit for the program you must use these three topics. You are to write a program that will read a series of names of people from a data file that has been created with extra blank spaces and reformat the names into a standardized format. The datafile is mp6names.txt. It is arranged with the information for one person on each line....
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT