I'm trying to understand why I am getting this TypeError
when instantiating my deque
. I am solving the "Number of Islands" problem
def bfs(r,c):
q = collections.deque((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
r_next, c_next = r_curr dr, c_curr dc
if is_valid(r_next, c_next):
visited.add((r_next, c_next))
q.append((r_next, c_next))
Gives me the below error:
TypeError: cannot unpack non-iterable int object
r_curr, c_curr = q.popleft()
But the below works without error.
def bfs(r,c):
q = collections.deque()
q.append((r,c))
while q:
r_curr, c_curr = q.popleft()
for dr, dc in dirs:
r_next, c_next = r_curr dr, c_curr dc
if is_valid(r_next, c_next):
visited.add((r_next, c_next))
q.append((r_next, c_next))
Why does the first method fail but the second method works?
CodePudding user response:
You are getting the error when popleft
ing from deque
not when instantiating it. Because your deque has two elements at the start (r
and c
) not one tuple (r, c)
. To have a tuple in deque initialize it like so:
q = collections.deque([(r,c)])
CodePudding user response:
deque
takes an iterable, using the elements to form itself. So deque((r, c))
gives you the deque equivalent of (r, c)
. You want this to be a deque with one item: (r, c)
, not two items: r
and c
, so you must use deque(((r, c),))
.