In: Computer Science
Python 3.7:
1. Write a generator expression that repeats each character in a given string 4 times. i.e. given “gone”, every time you call the next method on the generator expression it will display “gggg”, then “oooo”, … etc and instantiate it to an object called G. G = (…..) # generatorExpression object
2. Test and verify that iter(G) and G are the same things. What does this tell you about the nature of a Generator object/expression?
3. Assign Iter(G) to an iterator object called it1 and advance it to the next element by using next method.
4. Instantiate a new Iter(G) object called it2. Use the next method and advance it to the next element. Observe the result and compare it with the results of it1.
5. Does the new Iter(G) object start the iterator from the start of the string object? Write down your understanding/conclusion from this experiment.
6. How can you get back the Iter(G) to point back to the beginning of the string?
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code
#defining a text to be used
text="gone"
#creating the required generator object that will return each
character in text
#4 times in each iteration (part 1)
G=(i*4 for i in text)
#verifying that G and iter(G) are same (part 2) This proves
that generators
#are in fact iterators. if you print G and iter(G), you can see
that both
#objects point to the same object in same memory
print(G==iter(G)) #should be True
#creating an iterator for G and assigning to it1 (part
3)
it1=iter(G)
#printing next value of it1 (should be 'gggg')
print(next(it1))
#creating an iterator for G and assigning to it2 (part
4)
it2=iter(G)
#printing next value of it2 (should be 'oooo')
print(next(it2))
'''
5. Does the new Iter(G) object start the iterator from the start of
the string object?
Answer: No it doesn't. This is because a generator can be iterated
only once. Each iter()
calls return the same object in memory, so calling next on it2 will
automatically call next
on it1 because both are same.
6. How can you get back the Iter(G) to point back to the beginning
of the string?
Answer: The one and only way to do this is to re initialize the
generator, pass the same
expression we used to create the generator (i*4 for i in text) in
order to restart it.
if you put that expression inside a method, then we can just call
that method whenever we
want to restart the generator. There is literally no other
way.
'''
#output
True
gggg
oooo