PyTricks icon indicating copy to clipboard operation
PyTricks copied to clipboard

Add iterating over initial array in reverse order.

Open askanium opened this issue 5 years ago • 5 comments

askanium avatar Jun 10 '19 07:06 askanium

Iterating over an array without modifying it is elementary python. Doing it efficiently can be considered as a "trick" (or rather, good knowledge of python)

Try the benchmark :

%alias_magic t timeit
L = [x for x in range(3000000)] 
%t for e in reversed(L) : e
%t for e in L[::-1] : e
%t for i in range(len(L)-1, 0, -1): L[i]

also note that reversed can be used with any iterable, not only list

flintforge avatar Jun 10 '19 16:06 flintforge

Depends on the definition of efficiently.

From a Time Complexity perspective, you are completely right, the solution I suggested is inferior.

From a Space Complexity perspective, both existing solutions take O(n) space, while mine takes O(1) space.

Time Complexity is more important than Space Complexity in most of the cases, as space is cheap, but for some specific cases, knowing how to iterate without duplicating the array might save the day.

Having said this, I don't mind if you close this PR if you think it doesn't bring value, just wanted to explain why I created it in the first place.

askanium avatar Jun 10 '19 18:06 askanium

There are many perspectives but, generally speaking, only one acceptable definition : https://www.lexico.com/en/definition/efficiently

Are you assuming that L[::-1] and reversed(L) are effectively reversing the list ?

Reversed is a type in the Python implementation.

And the function reversed() returns an iterator : https://docs.python.org/3/library/functions.html#reversed, not a new list.

I think you can improve the example to show that both possibilities exists and that reversed performs faster (which is perfectly logical and without consuming any space)

flintforge avatar Jun 10 '19 19:06 flintforge

I don't see how the definition you posted contradicts my comment about it. Saying "this algorithm is efficient time-wise" and "this algorithm is efficient space-wise" is perfectly valid and describes more accurately what type of efficiency was achieved.

Indeed, while reversed returns an iterator, L[::-1] does return a slice object, which takes up O(n) space. There is itertools.islice to obtain an iterator instead, but the syntax of doing that won't be so short anymore.

askanium avatar Jun 11 '19 04:06 askanium

what about mentioning this notes in the code ? That would be very instructive for newcomers, doesn't it ?

flintforge avatar Jul 05 '19 22:07 flintforge