2
   for sentence in self.knowledge:
       ...
       else:
              safes=sentence.known_safes()
              if(safes!=None):
                  for safe in safes:
                      self.mark_safe(safe)

knowledge is a list of objects of a class Sentence where each object has a set of cells and a corresponding count

I am getting runtime error RuntimeError: Set changed size during iteration

This is how known_safes looks like:

def known_safes(self):
    if self.count == 0:
        return self.cells

This is the function mark_safe of Sentence class:

def mark_safe(self, cell):
    if(cell in self.cells):
       self.cells.discard(cell)

This is the function mark_safe of MinesweeperAI class:

def mark_safe(self, cell):
    """
    Marks a cell as safe, and updates all knowledge
    to mark that cell as safe as well.
    """
    self.safes.add(cell)
    for sentence in self.knowledge:
        sentence.mark_safe(cell)

Also, I understand that sets cant be changed while iterating over them in python.However in java we always modify arrays in loops. What is the logic behind not operating on objects while iterating over them ?

Sanjanah
  • 21
  • 3
  • "However in java we always modify arrays in loops." [No, you don't](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re). – Karl Knechtel Jun 28 '20 at 07:31
  • Anyway, it is the same idea as https://stackoverflow.com/questions/742371/why-does-python-skip-elements-when-i-modify-a-list-while-iterating-over-it , except that the implementation of a set iterator can't just use an index (because the internal structure is more complicated), so it can't just skip elements but has to raise an exception instead (because the iterator's state is invalid). – Karl Knechtel Jun 28 '20 at 07:33

0 Answers0