This is a dfs search implemented using python which i have taken from internet
<pre><code>graph={
       'A':set(['B','C']),
       'B':set(['A','D','E']),
       'C':set(['A','F']),
       'D':set(['B']),
       'E':set(['B','F']),
       'F':set(['C','E'])}

def dfs(graph, start):
      visited, stack = set(), [start]

      while stack:
             vertex = stack.pop()
             if vertex not in visited:
                       visited.add(vertex)
                       stack.extend(graph[vertex] - visited)

     return visited

dfs(graph, 'A')
</code></pre>

<p>Can anyone explain why we are using these</p>

<ol>
<li><code>visited,stack = set(), [start]</code></li>
<li><code>graph[vertex] - visited</code></li>
<li><code>stack.extend(graph[vertex] - visited)</code></li>
</ol>

<p>The first line you're asking about is initializing the <code>visited</code> and <code>stack</code> variables. You could write it on two lines if you wanted to:</p>

<pre><code>visited = set()
stack = []
</code></pre>

<p>I like initializing things on separate lines a bit better, but it's mostly a matter of style. I know a lot of other Python programmers like to combine their initializations, probably because it lets them use fewer lines (which becomes especially valuable if your function grows longer than you can see on one screen at a time). Both versions work fine.</p>

<p>The second thing you ask about is a <code>set</code> subtraction expression. In this case, it's subtracting <code>visited</code> from <code>graph[vertex]</code>, which is a <code>set</code> containing the neighbors of <code>vertex</code>. The difference operation finds all the values in <code>graph[vertex]</code> that are not also in <code>visited</code>, and returns a <code>set</code> containing them.</p>

<p>The third thing you ask about is a <code>list.extend</code> call. This appends each of the values from the <code>set</code> subtraction onto <code>stack</code> (which is a list). You could write a loop and repeatedly call <code>append</code> instead of the one call to <code>extend</code>, but there's really no reason to do that in this situation. <code>set</code>s are iterable, but it's worth noting that they yield their items in arbitrary order, so you can't tell ahead of time exactly which order the items will end up in when they're in the list. Fortunately, order doesn't matter for this algorithm.</p>

<p>It's also worth noting that the function would still work without the set subtraction. It would just be a little bit less efficient, since more values would get added to the <code>stack</code> only to be skipped (since they've already been <code>visited</code>) when they get popped off the stack later.</p>

python