PyTricks
PyTricks copied to clipboard
Add iterating over initial array in reverse order.
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
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.
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)
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.
what about mentioning this notes in the code ? That would be very instructive for newcomers, doesn't it ?