I am trying to have a queue using deque in python.
The error I keep getting is index out of range
perf_his[b][c] = 0
IndexError: deque index out of range
Here is a small prototype of the code that I implemented.
import collections
apps = [1,2,3]
num_thrs = len(apps)
perf_his = []
for a in range(num_thrs):
perf_his += [collections.deque(maxlen=1)]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b][c] = 0
Inorder to check if I did understand deque correctly, I implemented this code:
#!/usr/bin/env python
from collections import deque
something = ["foo","bar","baz"]
output = []
diff = 0
d = deque()
for i in something:
d.append(i)
print("-> %s" % i)
for i in xrange(len(d)):
print(d[i])
output.append(d[i])
for i in xrange(len(something)):
if output[i] != something[i]:
diff += 1
print(something,output,diff)
I've been trying to fix the error in like 2 days, I don't seem to understand the problem. can someone please shed some light?
In your first bit of code, you never append() to the deque, and thus it never has an element "0", and thus you aren't allowed to assign to it. Setting maxlen doesn't create elements, it just limits how many elements can be present later on.
What you probably want instead is this:
for a in range(num_thrs):
perf_his += [collections.deque()]
for b in range(num_thrs):
for c in range(0, 1):
perf_his[b].append(0)
When maxlen is set, the deque still is size zero until elements are added. The effect of maxlen=5 is that after five appends, then next append will automatically pop the oldest element so that the size never get bigger. In other words, maxlen is the maximum size, not the minimum.
For your application, the deque needs to be prepopulated with initial values before you can make any assignments:
>>> d = deque([0] * 5, maxlen=5)
>>> d[2] = 100
>>> d
deque([0, 0, 100, 0, 0], maxlen=5)
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