Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

This five part assignment offers practice iterating over lists, ranges, and strings using for and while loops as well as using a generator of random

This five part assignment offers practice iterating over lists, ranges, and strings using for and while loops as well as using a generator of random integers. It's also a good exercise in writing unittest test cases.

Part 1:count_vowels(seq)

Make functioncount_vowels(s)that takes a string as an argument and returns the number of vowels('a', 'e', 'i' 'o', 'u')in the string. Should you use afororwhileloop? (Implement this as a function, not as a class with a method.)

Be sure to include unittest test cases to demonstrate that your code works properly, e.g.

def count_vowels(s: str) -> int: return 0 # Your definition goes here  class CountVowelsTest(unitttest.TestCase): def test_count_vowels(self) -> None: self.assertEqual(count_vowels('hello world'), 3) Hint: Python offers an 'in' operator that evaluates to True or False, e.g. "a" in ['a', 'e', 'i', 'o', 'u'] 

evaluates toTrue.

Hint: Strings can easily be converted to all lower case with thestring.lower()method, e.g."HeLlO wOrLd".lower() == "hello world"

Part 2:last_occurrence(target, sequence)

Make a functionlast_occurrence(target: Any, sequence: Sequence[Any]) -> Optional[int]that takes two arguments:

  1. target: A target item to find
  2. sequence: A sequence of values, e.g. a list is a sequence as is str.

Your function should return theindex(offset from 0) of thelastoccurrence of the target item orNoneif the target is not found. E.g. the last occurrence of 33 is at offset 3 in the list[ 42, 33, 21, 33 ]because 42 is offset 0, the first 33 is at offset 1, 21 is offset 2, and the last 33 is offset 3.

Hints:

  • How do we specify the type hint for a function that returns either an integer or None?
from typing import Optional def foo() -> Optional[int]: # return an int or None return None 
  • How can we specify the type hint for a variable/parameter/return type of an arbitrary sequence that matches list or str or other sequences?
 from typing import Sequence, Any my_seq: Sequence[Any] # my_seq is a sequence of values of Any type 

Use unittest to test your function with several different target values and lists.

Next, test your function with a character as the target, and a string as the list, e.g.find('p', 'apple'). What should happen?

Be sure to use unittest to demonstrate that your code works properly.

Part 3:Fraction.simplify()

The fractions in Homework03 are correct, but not simplified, e.g.2/4 can be simplified to 1/2, 14/21 can be simplified to 2/3, and 63/9 can be simplified to 7/1. Recall from elementary school that you can simplify fractions by finding the Greatest Common Factor (GCF) and then dividing the number and denominator. Here's pseudocode for one solution:

 start = the min of abs(numerator) and abs(denominator) # the absolute value is important for negative values for each integer gcf from start down to 2 if numerator mod gcf == 0 and denominator mod gcf == 0 then gcf is the greatest common factor that evenly divides both the numerator and denominator return a new Fraction with numerator / gcf and denominator / gcf if you don't find a gcf, then return a copy of the Fraction because it can't be simplified 

Extend your Fractions with a new method,Fraction.simplify()class from HW03 and add a newsimplify(self)method that returns a new Fraction that is simplified or just returns a copy of self if self can't be simplified. E.g.

str(Fraction(9, 27).simplify()) == str(Fraction(1, 3)) 

Hint: Note that testing

Fraction(9, 27).simplify() == Fraction(1, 3) 

is not sufficient because

Fraction(9, 27) == Fraction(1, 3) 

Add unittest cases to test your new method.

Hint: what happens if the fraction has a negative numerator or denominator?

Hint: YourFraction.simplify()method shouldNOTmodify self, but should return a new instance of class Fraction with the appropriate numerator and denominator.

NOTE: YouMAY NOTuse Python's gcd() function. Implement your own.

Part 4:my_enumerate(seq)

Recall that Python's built-inenumerate(seq)function is a generator that returns two values on each call tonext(): the offset of the value and the value. E.g.

for offset, value in enumerate("hi!"): print(offset, value) 

generates the output:

0 h 1 i 2 ! 

Make a generator,my_enumerate(seq: Sequence[Any]) -> Iterator[Any]that provides the same functionalityWITHOUTcalling the built-inenumerate(). Be sure to include an automated test to validate your solution.

Hint: Generatorsyieldresults while functionsreturnresults.

Hint: Your automated test may comparelist(my_enumerate(your_sequence))to the expected output. E.g.

list(my_enumerate(your_sequence)) == list(enumerate(your_sequence)) 

Note from Benji: I used 2 lines of code (not including docstring) to implement the function - I got a one-liner solution but two-line solution is actually more readable ;-)

Hints:

The type hint for generators is

 from typing import Iterator def my_generator() -> Iterator[int]: # my_generator is a generator that yields a sequence of int values 

The type hint for arbitrary sequences is

  from typing import Sequence, List any_seq_any_values: Sequence[Any] # any sequence, e.g. list, str, tuple, etc of any values any_seq_int: Sequence[int] # any sequence, e.g. list, str, tuple, etc of ints list_of_ints : List[int] # a list of int values list_of_strings : List[str] # a list of str values 

I need toseparate my code into two files- one for code logic and one for unit test. It's always a good practice to separate the code and the test.

InFile1.pyyou should have:

  1. count_vowels()- function
  2. last_occurrence(target, sequence)- function
  3. my_enumerate(seq)- function

InFile2.pyyou will have three or four test classes:

  1. CountVowelsTest
  2. FindLastTest
  3. EnumerateTest

Download link for previous assignment which uses the functions and fractions needed: https://drive.google.com/file/d/1CREd8ujDb8UeZ7OB1hAch65yJ8CDsN9_/view?usp=sharing

The assignment linked above is a fraction calculator that cannot simplify fractions well.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Programming questions