def stack_search(start, expand, mode='bfs', build_inv=False):
 if (mode not in ('bfs', 'dfs')):
  raise ValueError('mode should be bfs or dfs', mode)
 rval_set = set()
 rval_list = list()
 if (mode == 'bfs'):
  start_pop = start.popleft
 else:
  start_pop = start.pop
 expand_inv = {}
 while start:
  l = start_pop()
  if (id(l) not in rval_set):
   rval_list.append(l)
   rval_set.add(id(l))
   expand_l = expand(l)
   if expand_l:
    if build_inv:
     for r in expand_l:
      expand_inv.setdefault(r, []).append(l)
    start.extend(expand_l)
 assert (len(rval_list) == len(rval_set))
 if build_inv:
  return (rval_list, expand_inv)
 return rval_list

def stack_search ( start , expand , mode = 'bfs' , build_inv = False ) : if ( mode not in ( 'bfs' , 'dfs' ) ) : raise ValueError ( 'mode should be bfs or dfs' , mode ) rval_set = set ( ) rval_list = list ( ) if ( mode == 'bfs' ) : start_pop = start . popleft else : start_pop = start . pop expand_inv = { } while start : l = start_pop ( ) if ( id ( l ) not in rval_set ) : rval_list . append ( l ) rval_set . add ( id ( l ) ) expand_l = expand ( l ) if expand_l : if build_inv : for r in expand_l : expand_inv . setdefault ( r , [ ] ) . append ( l ) start . extend ( expand_l ) assert ( len ( rval_list ) == len ( rval_set ) ) if build_inv : return ( rval_list , expand_inv ) return rval_list
search through a graph .