Advanced Python Development Course
Chapter
>
Level
Generators
Sending data to a Generator
Objective
Gather wool and spin it into yarn using the spindles by sending data into a generator.
Some of the sheep are getting a bit too wooly, it would be best to shear them and gather their wool. You can then put the wool through a spindle in order to produce yarn. To achieve this we would need to use a generator as the amounts of yarn and wool processed can vary greatly.
First define a generator capable of spinning yarn, naming it spin(), this generator need’s to be set up to use external input in order to operate. It reads data from yield and places it in a variable, then modifies it’s content by increasing it’s length with each cycle, finally producing a result.
def spin():
cycle = 1
while True:
cycle += 1
yarn = yield
yarn = yarn * cycle
yield player.speak("You've spun %d ft of yarn" % (yarn))
Because this is a generator, the while() statement inside can be paused and modified to produce the output we want, this level of control is at the heart of what a generator is and how it can be useful when processing data. To insert data into the generator, define it and use the send() function to feed it any data you desire, for example:
spindle = spin() # Create an instance of the generator next(spindle) # Run the generator a single step spindle.send(6) # Insert data into the generator # In this case you're sending it the number 6
Walk to the light X marks by the colored carpets and face the sheep. There is a dictionary constant named sheep that holds the value how much wool you can shear on each sheep. Use the speak() function with the dictionary and the color of the carpet you’re standing on, to shear sheep’s wool and check how much you’ve gathered. For example: player.speak(sheep["green"]) .
There are four (4) colored carpets in total: "green" , "red" , "blue" and "orange" . Once you have sheared the sheep, walk to the dark X marks by each colored carpet where the spindles are located. Use send() to enter the number of pounds of wool sheared from each sheep in their respective color into the generator.
For example, if when shearing the sheep in the "green" carpet, you shear 4 pounds of wool, go the "green" carpet by the spindles and send that data to the generator, like this:
next(spindle) spindle.send( 4)
Do this for all four (4) dark X marks on the colored carpets in order to complete the level.