Question

In: Computer Science

I just wrote Python code to solve this problem: Write a generator that will return a...

I just wrote Python code to solve this problem:

Write a generator that will return a sequence of month names. Thus

gen = next_month('October')

creates a generator that generates the strings 'November', 'December', 'January' and so on.
If the caller supplies an illegal month name, your function should raise a ValueError exception with text explaining the problem.

Here is my code:

month_names = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']

def next_month(name: str) -> str:
"Return a stream of the following months"
global month_names
while True:
try:
yield name
  
except StopIteration:
break

When I run this unit test below, I fail because it is not accepting lowercase 'december'. How can I fix this?

def test_months():
gen = next_month('October')
lst = [next(gen) for i in range(15)]
assert(lst == ['November', 'December', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January'])
  
gen = next_month('december')
assert next(gen) == 'January'
  
test_months()

Solutions

Expert Solution

CODE:

To fix that i have defined a new look up list where every element is conerted to lower case and compared.

Text:

month_names = ['January', 'February', 'March', 'April', 'May', 'June',

'July', 'August', 'September', 'October', 'November', 'December']

def next_month(name: str) -> str:

    "Return a stream of the following months"

    month_names_lookup = [mname.lower() for mname in month_names]

    index = month_names_lookup.index(name.lower())

    while True:

        try:

            index += 1

            yield month_names[index % len(month_names)]

        except StopIteration:

            break

    

def test_months():

    gen = next_month('October')

    lst = [next(gen) for i in range(15)]

    assert(lst == ['November', 'December', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January'])

    

    gen = next_month('december')

    assert next(gen) == 'January'

  

test_months()

For Handling Value error:


Related Solutions

I wrote this code and just realized I need to put it into at least 6...
I wrote this code and just realized I need to put it into at least 6 different functions and I don't know how. No specific ones but recommended is: Read Data, Calculate Installation Price, Calculate Subtotal, Calculate Total, Print -> 1) Print Measurements & 2) Print Charges. Can somebody help? #include <stdio.h> // Function Declarations int length, width, area, discount; int main () { // Local Declarations double price, cost, charge, laborCharge, installed, amtDiscount, subtotal, amtTax, total; const double tax...
Write a python script to solve the 4-queens problem using. The code should allow for random...
Write a python script to solve the 4-queens problem using. The code should allow for random starting, and for placed starting. "The 4-Queens Problem[1] consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal." Display the iterations until the final solution Hill Climbing (your choice of variant)
in python, sorry i thought i wrote it Write an interactive program that repeatedly asks the...
in python, sorry i thought i wrote it Write an interactive program that repeatedly asks the user to input a number until”Enter” is hit. Your program should create a file named “numbers.txt” where all the numbersare written one below the other, and the last line should display the sum of all the input, afterthe string “The sum of your numbers is ”.For example, if the user inputs 3, 5, 7, 10, -3, 5.2, then the file “numbers.txt” should contain: 3...
So I have written a code for it but i just have a problem with the...
So I have written a code for it but i just have a problem with the output. For the month with the highest temperature and lowest temperature, my code starts at 0 instead of 1. For example if I input that month 1 had a high of 20 and low of -10, and every other month had much warmer weather than that, it should say "The month with the lowest temperature is 1" but instead it says "The month with...
Using python as the coding language please write the code for the following problem. Write a...
Using python as the coding language please write the code for the following problem. Write a function called provenance that takes two string arguments and returns another string depending on the values of the arguments according to the table below. This function is based on the geologic practice of determining the distance of a sedimentary rock from the source of its component grains by grain size and smoothness. First Argument Value Second Argument Value Return Value "coarse" "rounded" "intermediate" "coarse"...
In Python I have a code: here's my problem, and below it is my code. Below...
In Python I have a code: here's my problem, and below it is my code. Below that is the error I received. Please assist. Complete the swapCaps() function to change all lowercase letters in string to uppercase letters and all uppercase letters to lowercase letters. Anything else remains the same. Examples: swapCaps( 'Hope you are all enjoying October' ) returns 'hOPE YOU ARE ALL ENJOYING oCTOBER' swapCaps( 'i hope my caps lock does not get stuck on' ) returns 'I...
Please solve this problem, in c++ (algoritms) write code and explaination how to solve it! 1)...
Please solve this problem, in c++ (algoritms) write code and explaination how to solve it! 1) N numbers are given. The first K of them are sorted in ascending order, the remaining NK are also sorted in ascending order. Sort numbers in ascending order in O (N). Input data format N - number of numbers, K - number of numbers in the first half (sorted). Example input 10 6 1 2 5 6 8 9 3 4 7 12 Sample...
Write a complete and syntactically correct Python program to solve the following problem: Write a program...
Write a complete and syntactically correct Python program to solve the following problem: Write a program for your professor that allows him to keep a record of the students’ average grade in his class. The program must be written in accordance with the following specs: 1. The input must be interactive from the keyboard. You will take input for 12 students. 2. You will input the students’ name and an average grade. The student cannot enter an average below zero...
I have to write a random password generator in Python 3 and im having some trouble...
I have to write a random password generator in Python 3 and im having some trouble writing the code and i dont really know where to start. The prompt goes as such: The problem in this assignment is to write a Python program that uses functions to build (several options of) passwords for the user. More specifically, your program will do the following: 1. Prompt the user for the length of the password to be generated. Call this length lenP....
Use Python to solve, show all code Write a program that sums a sequence of integers...
Use Python to solve, show all code Write a program that sums a sequence of integers from a starting integer to and ending integer. The sequence is generated by skipping a value (e.g. 1,3,5,… or 2,6,10,14…). Prompt the user for a) a starting value greater than 0. Validate the value is greater than 0. b) the ending value. c) the value to skip Print out the sum of the numbers for the sequence. If the starting value is 2, the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT