On Thu, 4 May 2023 at 07:43, Thomas Passin <li...@tompassin.net> wrote: > > On 5/3/2023 3:46 PM, Oscar Benjamin wrote: > > On Wed, 3 May 2023 at 18:52, Thomas Passin <li...@tompassin.net> wrote: > >> > >> On 5/3/2023 5:45 AM, fedor tryfanau wrote: > >>> I've been using python as a tool to solve competitive programming problems > >>> for a while now and I've noticed a feature, python would benefit from > >>> having. > >>> Consider "reversed(enumerate(a))". This is a perfectly readable code, > >>> except it's wrong in the current version of python. That's because > >>> enumerate returns an iterator, but reversed can take only a sequence type. > >> > >> Depending on what you want to give and receive, enumerate(reversed(a)) > >> will do the job here. Otherwise list() or tuple() can achieve some of > >> the same things. > > > > I don't think that is equivalent to the intended behaviour: > > > > reversed(enumerate(a)) # zip(reversed(range(len(a))), reversed(a)) > > enumerate(reversed(a)) # zip(range(len(a)), reversed(a)) > > I don't think we know the intended behavior here. The OP did not say > what type of object should be returned. He only wanted an expression > that would run. Apparently the result should be an enumeration of > variable "a" but with "a" reversed. Is "a" supposed to be a sequence? > An iterator? Presumably the result was expected to be an enumeration, > which is to say an iterator, and enumerate(reversed(a)) would return an > iterator.
The part you're probably missing here can be easily shown: >>> a = [10, 20, 30, 40, 50] >>> for i, n in enumerate(reversed(a)): ... print("E-R", i, n) ... E-R 0 50 E-R 1 40 E-R 2 30 E-R 3 20 E-R 4 10 >>> for i, n in reversed(list(enumerate(a))): ... print("R-E", i, n) ... R-E 4 50 R-E 3 40 R-E 2 30 R-E 1 20 R-E 0 10 So a closer equivalent would be: >>> for i, n in zip(reversed(range(len(a))), reversed(a)): ... print("Zip", i, n) ... Zip 4 50 Zip 3 40 Zip 2 30 Zip 1 20 Zip 0 10 Note that it's reversing both the indices and the values. ChrisA -- https://mail.python.org/mailman/listinfo/python-list