+ 13

Explain how you reverse a generator?

I confused because its not reversed(), but how?

27th Aug 2019, 9:29 PM
Blue Blitz Coder
Blue Blitz Coder - avatar
6 Réponses
+ 17
You cannot reverse a generator in any generic way except by casting it to a sequence and creating an iterator from that. Later terms of a generator cannot necessarily be known until the earlier ones have been calculated. Even worse, you can’t know if your generator will ever hit a StopIteration exception until you hit it, so there’s no way to know what there will even be a first term in your sequence. The best you could do would be to write a reversed_iterator function: def reversed_iterator(iter): return reversed(list(iter)) You could also, of course, replace reversed in this with your imap based iterative version, to save one list creation.
27th Aug 2019, 9:30 PM
Green Ghost
Green Ghost - avatar
+ 10
def reversed_iterator(iter): return reversed(list(iter))
27th Aug 2019, 9:55 PM
Coding Person
Coding Person - avatar
+ 8
Is this the sort of thing you mean:- def rev_gen(): for x in range(100, 0, -1): yield x for x in rev_gen(): print(x)
27th Aug 2019, 9:57 PM
rodwynnejones
rodwynnejones - avatar
+ 8
Use imap is what I'd do.
27th Aug 2019, 10:26 PM
Regulation
Regulation - avatar
+ 5
Don't spam Guna please!
29th Aug 2019, 12:30 AM
Bob Brown
Bob Brown - avatar
- 1
ghj
28th Aug 2019, 5:58 AM
Guna Sekaran
Guna Sekaran - avatar