I am trying to write a function that gets a set of tuples as parameter, and checks if given characters form a continuous shape in an NxN grid. Tuples are the indexes of characters in the lists that form the grid. The shape is continuous if there is a character directly below, above or to the sides of another character.
continuous not continous not continous
xxxxx xxxxx ooxxx
xxoox xxoox xxxxx
xxxoo ooxxx xxoox
xxxoo oxxxx xxoox
xxxxo xoxxx xxxxx
========================
def connected(characters):
result = True
for i in characters:
if (i[0]+1, i[1]) in characters or (i[0]-1, i[1]) in characters or (i[0], i[1]+1) in characters or (i[0], i[1]-1) in characters:
result = True
characters.discard(i)
else:
result = False
return result
return result
>>>connected({(1, 3), (2, 1), (2, 3), (0, 3), (1, 1)})
would form this shape, thus it wouldn't be continuous but my code thinks it is.
xxxo
xoxo
xoxo
xxxx
This works for the most time, but doesn't work when given characters form two separate continuous shapes like the 2nd wrong example I gave above. I tried to solve this problem by removing each tuple after it was checked but I get
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/untitled6/venv/1.py", line 47, in <module>
connected({(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)})
File "C:/Users/User/PycharmProjects/untitled6/venv/1.py", line 15, in connected
for i in grid:
RuntimeError: Set changed size during iteration
error. What can I do to solve this?