Videos
When you grab the current node from the front of the queue in python BFS implementation, you are usually using pop(0) on an array. This requires a O(n) reshuffling. Wouldn’t this resolve to polynomial time complexity? If I am wrong, can someone explain why.
I have a deque that consists of datetime objects (the rightmost elements will always be newer) and I'm trying to write some logic to pop items older than n seconds off the queue. I have it sort of functioning, but my while loop depends on looking at the -1 element of the queue, which doesn't always exist (in the case where it has been emptied because all items in the queue were older than the threshold). I can get around it with some try/except stuff or more conditionals, but none of that seems very pythonic.
while True:
targettime = datetime.now() - timedelta(seconds=5 * 60)
while queue[-1] >= targettime and len(queue) > 0:
queue.pop()
if len(queue) == 0:
do_work()
time.sleep(60)Any advice on how to handle this better? I'm open to entirely new solutions as well, using a deque seemed like the best approach but now I'm not so sure.
Python's list implementation uses a dynamically resized C array under the hood, removing elements usually requires you to move elements following after up to prevent gaps.
list.pop() with no arguments removes the last element. Accessing that element can be done in constant time. There are no elements following so nothing needs to be shifted.
list.pop(0) removes the first element. All remaining elements have to be shifted up one step, so that takes O(n) linear time.
To add to Martijn's answer, if you want a datastructure that has constant time pops at both ends, look at collections.deque.