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...
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...
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...
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....
In python please write the following code the problem. Write a function called play_round that simulates...
In python please write the following code the problem. Write a function called play_round that simulates two people drawing cards and comparing their values. High card wins. In the case of a tie, draw more cards. Repeat until someone wins the round. The function has two parameters: the name of player 1 and the name of player 2. It returns a string with format '<winning player name> wins!'. For instance, if the winning player is named Rocket, return 'Rocket wins!'.
Write a complete and syntactically correct Python program to solve the following problem: You are the...
Write a complete and syntactically correct Python program to solve the following problem: You are the payroll manager for SoftwarePirates Inc. You have been charged with writing a package that calculates the monthly paycheck for the salespeople. Salespeople at SoftwarePirates get paid a base salary of $2000 per month. Beyond the base salary, each salesperson earns commission on the following scale: Sales Commission Rate Bonus <$10000 0% 0 $10000 – $100,000 2% 0 $100,001 - $500,000 15% $1000 $500,001 -...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT