Cyclic Iterator
Lesson 12 of 13 in Coddy's Python Iterators course.
Challenge
MediumCreate a ColorCycler class that implements a cyclic iterator for a list of colors. The class should have the following methods:
__init__(self, colors): Initialize the iterator with a list of colors.__iter__(self): Return the iterator object itself.__next__(self): Return the next color in the cycle.
After implementing the ColorCycler class, use it to generate a sequence of colors based on the input. The program should:
- Create a
ColorCyclerinstance with the input colors. - Generate and print a specified number of colors from the cycler.
The following input will be provided:
- A string of comma-separated colors
- An integer representing the number of colors to generate
Print each generated color on a new line.
Try it yourself
# Read input
colors = input().split(',')
num_colors = int(input())
class ColorCycler:
def __init__(self, colors):
# TODO: Initialize the ColorCycler
def __iter__(self):
# TODO: Implement __iter__ method
def __next__(self):
# TODO: Implement __next__ method
# TODO: Create a ColorCycler instance with the input colors
# TODO: Generate and print the specified number of colors
# Note: Remember to print each color on a new line