code: def graph_simplify(G):
      
      spurs = []
      path_nodes = []
      for k, d in G.degree().iteritems():
          if d == 1:
              spurs.append(k)
          elif d == 2:
              path_nodes.append(k)
  
      logging.debug("Remove {0} spurs.".format(len(spurs)))
      G.remove_nodes_from(spurs)
  
      SG = G.subgraph(path_nodes)
      cc = nx.connected_components(SG)
      for c in cc:
          if len(c) == 1:
              continue
          c = set(c)
          neighbors = set()
          for x in c:
              neighbors |= set(G.neighbors(x))
          neighbors -= c
          newtag = list(c)[0] + "*"
          for n in neighbors:
              G.add_edge(newtag, n)
          G.remove_nodes_from(c)
      logging.debug("Contract {0} path nodes into {1} nodes.".\
                      format(len(path_nodes), len(cc)))
docs: Simplify big graphs: remove spurs and contract unique paths.