How to look before a detex without jumping out?

I want to check the condition in front of the queue before deciding whether to pop. How can I achieve this in python using collection.deque?

list(my_deque)[0]

seems ugly and bad for performance.

+4
source share
2 answers

TL DR: assuming yours dequeis called d, just check d[-1], since the "rightmost" element in deque is the front (you can test it before the deck length to make sure it is not empty). Taking the @asongtoruin suggestion, use if d:to check if deque is empty (this is equivalent if len(d) == 0:, but more pythonic)

Why not convert to a list?

deque , . deque , , - . :

Deques -, O (1) .

, O (n) pop (0) (0, v) , , .

, "" . :

- O (1) , O (n) . .

list O (n), O (1).

+3

, my_deque[-1] my_deque[len(my_deque)-1].

0

Source: https://habr.com/ru/post/1693238/


All Articles