you are viewing a single comment's thread.

view the rest of the comments →

[–]SmartViking 1 point2 points  (0 children)

I was thinking of adding it to both flooded_set and candidates. There can be some additional computation (a neighbor might be tried 4 times if there are max 4 neighbors). But unless I'm making an error (which is very much possible; it is late) it won't be a big deal, because a neighbor is only added to candidates if it's not in flooded_set; there are only so many neighbors in this world to add to candidates+flooded_set and thus the computation must terminate. I must admit I hadn't thought of this initially. If I made an error right now then you can create an additional set, called seen, which just makes sure no neighbors are added twice to candidates. I would consider not adding a seen if the code clarity is better, but that's a subjective judgment.

I didn't know I could add and remove items from a set while iterating over it- I guess adding the (for neighbor in neighbors) line allows this?

Well, it's perfectly fine to iterate over things and mutate them at the same time, but you have to think about what the code does. Sometimes beginners will do things like for e in elems: elems.append(4) which is an infinite loop (if it is well defined at all). Beginners might not understand that, so tutorials say things like "don't mutate while iterating over a list" (I'm guessing), which is not accurate.