Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a generator expression that repeats each character in a given string 4 tim

ID: 3751335 • Letter: W

Question

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 • 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? • Assign Iter(G) to an iterator object called it1 and advance it to the next element by using next method. • 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. • Does the new Iter(G) object start the iterator from the start of the string object? Write down your understanding/conclusion from this experiment. • How can you get back the Iter(G) to point back to the beginning of the string?

Explanation / Answer

Please find the answers for your questions below. Drop a comment if you have any doubts. Thank you

#this is the required generator expression,

#replace 'gone' with whatever text you want

#c*4 will return 4 times a character from 'gone' every time

G=(c*4 for c in 'gone')

#two statements below will print the same thing, meaning that iter(G) and G are the same thing

print(iter(G))

print(G)

print(iter(G) == G) # will print True

'''this means that a generator expression does not create a list object, rather it produces an iterable generator object'''

#creating an iterator from G

it1=iter(G)

#printing next value

print(next(it1)) #gggg

#creating another iterator from G

it2=iter(G)

#printing next value of this iterator

print(next(it2)) #oooo

'''Observing the above results, we can say that the new iterator it2 does not start from the start of the string, but from the current value'''

''' We cannot make iter(G) point back to the beginning of string directly, as generators can't be rewound. Indirect ways of implementing this include defining a generator function and setting up cases for starting from the beginning if a condition is met'''

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote