In: Computer Science
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()
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: