reversed() , [::-1] . , , .
import queue
s = "abc"
lst = list(s)
iter_ = iter(s)
, reversed():
def reversed_iter(iterable):
"""Yield items in reverse with a queue."""
stack = queue.LifoQueue()
for x in iterable:
stack.put(x)
while not stack.empty():
yield stack.get()
list(reversed_iter(s))
# ['c', 'b', 'a']
list(reversed_iter(lst))
# ['c', 'b', 'a']
list(reversed_iter(iter_))
# ['c', 'b', 'a']
- , . .
β β
| "c" |
| "b" |
| "a" |
-----------
( ) ( ), , "c".
:
- ( ,
LifoQueue)
The result is the elements obtained in the reverse order.
queuenot required. Alternatively, we can emulate the stack with a simple one list:
def reversed_iter(iterable):
"""Yield items in reverse with a list."""
stack = []
for x in iterable:
stack.append(x)
while stack:
yield stack.pop()
list(reversed_iter(s))
Emulating an abstract data type is all that is needed in both examples.
source
share