Generators 3 – Design of Computer Programs

Generators 3 – Design of Computer Programs


Okay. Let’s just run this. I was getting sick of writing out 1,000,001, so I’m just going to do 11 now. So you see when we run this, we get what’s called a generator object. It says “genexpr,” and that’s a memory location. We’ve created a generator object. Let’s see what we can do with it. Let’s actually make an assignment here. Now g is this generator object, and basically all it means to be a generator object is that this object can be iterated over, which basically means we can call this next function on it. If I call next on g, hit enter, I get zero. That’s zero squared as I would expect. If I do it again, 1, which is 1 squared, and so on until i get to 10, which is the last number is my range, and then of course stop iteration as you saw in class. But next isn’t the only function that does this sort of iteration. Let’s reassign g, because now that we’ve gotten to this stop iteration g is sort of spent. So we’ve reassigned it, and let’s take the sum of g. Sum performs the iteration for us. We could also do a for loop, and that does exactly what we’d expect. How else can we get one of these generator objects besides using a generator expression? Well, we can define a function. This function “gensquares” does the exact same thing as our previous generator expression. Note this yield statement. This is interesting. This is what makes it a generator function and not a normal function. Of course, if we call gensquares right now, we’ll see that this is a function. But the reason why it behaves differently is because of this yield statement. Basically, the main difference between yield and return is that when a generator reaches a yield statement it suspends execution and remembers the state of all local variables. That’s really important. This memory of the local variables allows it to pick up where it left off when we call, for example, next on it again. So we have our generator function. How can we get a generator object out of that? Well, we just have to call the function. Let’s call it with an argument of–I don’t know–let’s say 11. There we go. There’s our generator object. Just like before, we can call next. Here we get zero as expected. If I call next one more time, what do you think the output will be? Do you think the output would be 0, 1, 4, or 121?

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2019 Geted Tabs Online. All rights reserved.