I am learning Python and have been trying to make a deque. However, I get incorrect output and I am not sure why. My code is as follows:
p = [2, 1], [1, 1]
init_q= deque()
init_q.append(p)
for i in range(len(p)):
for j in range(len(p[i])):
temp = p[i][j]
p[i][j] = 0
init_q.append(p)
p[i][j] = temp
while init_q:
print init_q.pop()
In this code I take in a list, I then want to create a queue with 5 list, 4 of which have a 0 in them at different locations, the result I want is:
([2, 1], [1, 1])
([0, 1], [1, 1])
([2, 0], [1, 1])
([2, 1], [0, 1])
([2, 1], [1, 0])
However, the result I get is:
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
([2, 1], [1, 1])
Unlike some other collections, a deque is fully iterable. This means that you can obtain a list of items by using a for loop whenever necessary.
For lists, it's always O(1). So, for accessing elements, lists are always a better choice, it's not at all what deques were designed for. Second, because deques are implemented as doubly-ended arrays, they have the advantage when appending or popping from both the right and the left side of a deque (measured as O(1)).
A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library. It has the methods for adding and removing elements which can be invoked directly with arguments.
Second, why isn't list slicing notation of any kind allowed on a python deque? There are just no types in the standard library where this makes sense. The deque type is a linked list and indexing past 0 and -1 is inefficient (read, takes O(N) time), so slicing those doesn't make much sense.
You are putting an object in the deque, then changing the object. In fact, you always put the same object into the deque, so all the deque has are references to one object p.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With