Hopcrof Karp algorithm does not work [python3]

They call me Inspector Morse

When stopping and starting a tile job, what to do with the extra thinset from previous row's cleanup?

PTIJ: Should I kill my computer after installing software?

Signed and unsigned numbers

Can one live in the U.S. and not use a credit card?

When a wind turbine does not produce enough electricity how does the power company compensate for the loss?

Does this video of collapsing warehouse shelves show a real incident?

weren't playing vs didn't play

Why the color red for the Republican Party

Sort with one element at the end

Is "history" a male-biased word ("his+story")?

Find longest word in a string: are any of these algorithms good?

When traveling to Europe from North America, do I need to purchase a different power strip?

Why does liquid water form when we exhale on a mirror?

Why does Captain Marvel assume the people on this planet know this?

Child Theme Path Being Ignored With wp_enqueue_scripts

Is compression "encryption" under FCC regs?

Should I take out a loan for a friend to invest on my behalf?

Counting all the hearts

meaning and function of 幸 in "则幸分我一杯羹"

Virginia employer terminated employee and wants signing bonus returned

What problems would a superhuman have whose skin is constantly hot?

How does one describe somebody who is bi-racial?

How is the wildcard * interpreted as a command?



Hopcrof Karp algorithm does not work [python3]














0












$begingroup$


Can some of you check what's wrong in my implementation of Hopcroft Karp algorithm to find maximum matching in a bipartite graph?



I implemented it as a method of my Graph() class, the method input consists in two lists or set of nodes (representing the two sets of nodes of a bipartite graph).
It seems that the code, SOMETIMES, isn't able to find an augmenting path. Sometimes instead it works, but it seems casual.



 class Graph:

def __init__(self, TarjanSCC = False, Directed = True):
self.TarjanSCC = TarjanSCC
self.Directed = Directed
self.Nodes = {}

def add_node(self,key):
self.Nodes[str(key)] = {,'AdjacencyList':{}}

def add_edge(self, start_node, target_node, weight = 1):
if(str(start_node) not in self.Nodes.keys()):
self.add_node(start_node)
if(str(target_node) not in self.Nodes.keys()):
self.add_node(target_node)
self.Nodes[str(start_node)]['AdjacencyList'][str(target_node)] = {'weight' : weight}
if not self.Directed:
self.Nodes[str(target_node)]['AdjacencyList'][str(start_node)] = {'weight' : weight}

def HopcroftKarp(self,u,v):
global U,V,M,unmatched_nodesU,unmatched_nodesV

U = set(map(str,u))
V = set(map(str,v))
if self.Directed:
raise Exception("Can't compute Hopcroft Karp algorithm for a DIRECTED graph.")
self._initializeHK()
while True:
AP = self._BFS_HK()
if not AP:
return M
else:
M = M ^ AP
unmatched_nodesU = U-set([el[0] for el in M])
unmatched_nodesV = V-set([el[1] for el in M])

def _initializeHK(self):
global U,V,M,unmatched_nodesU,unmatched_nodesV
M = set()
free_vertices = {el:True for el in V}
for el in U:
for node in self.Nodes[el]['AdjacencyList'].keys():
if node in free_vertices:
M.add((el,node))
del free_vertices[node]
break
unmatched_nodesU = U-set([el[0] for el in M])
unmatched_nodesV = V-set([el[1] for el in M])

def _BFS_HK(self):
global unmatched_nodesU
global unmatched_nodesV
global M
global U
global V
vis = set()
vis.clear()
queue = list(copy.deepcopy(unmatched_nodesU))
alt_g = Graph()
while queue:
tmp = queue.pop(0)
vis.add(tmp)
if tmp in U:
for succ in self.Nodes[tmp]['AdjacencyList'].keys():
if (tmp,succ) not in M and succ not in vis:
alt_g.add_edge(tmp,succ)
queue.append(succ)
else:
for succ in self.Nodes[tmp]['AdjacencyList'].keys():
if (succ,tmp) in M and succ not in vis:
alt_g.add_edge(tmp,succ)
queue.append(succ)
AP = self._DFS_HK(alt_g)
if AP:
return AP
else:
return None

def _DFS_HK(self,alt_g):
global unmatched_nodesU,visited,fathers
fathers = {}
fathers.clear()
visited = set()
visited.clear()
queue = list(copy.deepcopy(unmatched_nodesU))
for node in unmatched_nodesU:
if node not in visited and node in alt_g.Nodes.keys():
fathers[node] = None
AP = self._DFS_HK_xplore(alt_g,node)
if AP:
return AP
else:
continue
return None

def _DFS_HK_xplore(self,alt_g,node):
global U,V,M,unmatched_nodesV,fathers,visited
visited.add(node)
if node in unmatched_nodesV:
AP = []
t = node
while t != None:
AP.insert(0,t)
t = fathers[t]
return self._get_edges(AP)
for el in alt_g.Nodes[node]['AdjacencyList'].keys():
if el not in visited:
fathers[el] = node
return self._DFS_HK_xplore(alt_g,el)

def _get_edges(self,AP):
global U
edges = set()
edges.clear()
for i in range(1,len(AP)):
if AP[i-1] in U:
edges.add((AP[i-1],AP[i]))
else:
edges.add((AP[i],AP[i-1]))
return edges








share







New contributor




ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    Can some of you check what's wrong in my implementation of Hopcroft Karp algorithm to find maximum matching in a bipartite graph?



    I implemented it as a method of my Graph() class, the method input consists in two lists or set of nodes (representing the two sets of nodes of a bipartite graph).
    It seems that the code, SOMETIMES, isn't able to find an augmenting path. Sometimes instead it works, but it seems casual.



     class Graph:

    def __init__(self, TarjanSCC = False, Directed = True):
    self.TarjanSCC = TarjanSCC
    self.Directed = Directed
    self.Nodes = {}

    def add_node(self,key):
    self.Nodes[str(key)] = {,'AdjacencyList':{}}

    def add_edge(self, start_node, target_node, weight = 1):
    if(str(start_node) not in self.Nodes.keys()):
    self.add_node(start_node)
    if(str(target_node) not in self.Nodes.keys()):
    self.add_node(target_node)
    self.Nodes[str(start_node)]['AdjacencyList'][str(target_node)] = {'weight' : weight}
    if not self.Directed:
    self.Nodes[str(target_node)]['AdjacencyList'][str(start_node)] = {'weight' : weight}

    def HopcroftKarp(self,u,v):
    global U,V,M,unmatched_nodesU,unmatched_nodesV

    U = set(map(str,u))
    V = set(map(str,v))
    if self.Directed:
    raise Exception("Can't compute Hopcroft Karp algorithm for a DIRECTED graph.")
    self._initializeHK()
    while True:
    AP = self._BFS_HK()
    if not AP:
    return M
    else:
    M = M ^ AP
    unmatched_nodesU = U-set([el[0] for el in M])
    unmatched_nodesV = V-set([el[1] for el in M])

    def _initializeHK(self):
    global U,V,M,unmatched_nodesU,unmatched_nodesV
    M = set()
    free_vertices = {el:True for el in V}
    for el in U:
    for node in self.Nodes[el]['AdjacencyList'].keys():
    if node in free_vertices:
    M.add((el,node))
    del free_vertices[node]
    break
    unmatched_nodesU = U-set([el[0] for el in M])
    unmatched_nodesV = V-set([el[1] for el in M])

    def _BFS_HK(self):
    global unmatched_nodesU
    global unmatched_nodesV
    global M
    global U
    global V
    vis = set()
    vis.clear()
    queue = list(copy.deepcopy(unmatched_nodesU))
    alt_g = Graph()
    while queue:
    tmp = queue.pop(0)
    vis.add(tmp)
    if tmp in U:
    for succ in self.Nodes[tmp]['AdjacencyList'].keys():
    if (tmp,succ) not in M and succ not in vis:
    alt_g.add_edge(tmp,succ)
    queue.append(succ)
    else:
    for succ in self.Nodes[tmp]['AdjacencyList'].keys():
    if (succ,tmp) in M and succ not in vis:
    alt_g.add_edge(tmp,succ)
    queue.append(succ)
    AP = self._DFS_HK(alt_g)
    if AP:
    return AP
    else:
    return None

    def _DFS_HK(self,alt_g):
    global unmatched_nodesU,visited,fathers
    fathers = {}
    fathers.clear()
    visited = set()
    visited.clear()
    queue = list(copy.deepcopy(unmatched_nodesU))
    for node in unmatched_nodesU:
    if node not in visited and node in alt_g.Nodes.keys():
    fathers[node] = None
    AP = self._DFS_HK_xplore(alt_g,node)
    if AP:
    return AP
    else:
    continue
    return None

    def _DFS_HK_xplore(self,alt_g,node):
    global U,V,M,unmatched_nodesV,fathers,visited
    visited.add(node)
    if node in unmatched_nodesV:
    AP = []
    t = node
    while t != None:
    AP.insert(0,t)
    t = fathers[t]
    return self._get_edges(AP)
    for el in alt_g.Nodes[node]['AdjacencyList'].keys():
    if el not in visited:
    fathers[el] = node
    return self._DFS_HK_xplore(alt_g,el)

    def _get_edges(self,AP):
    global U
    edges = set()
    edges.clear()
    for i in range(1,len(AP)):
    if AP[i-1] in U:
    edges.add((AP[i-1],AP[i]))
    else:
    edges.add((AP[i],AP[i-1]))
    return edges








    share







    New contributor




    ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      Can some of you check what's wrong in my implementation of Hopcroft Karp algorithm to find maximum matching in a bipartite graph?



      I implemented it as a method of my Graph() class, the method input consists in two lists or set of nodes (representing the two sets of nodes of a bipartite graph).
      It seems that the code, SOMETIMES, isn't able to find an augmenting path. Sometimes instead it works, but it seems casual.



       class Graph:

      def __init__(self, TarjanSCC = False, Directed = True):
      self.TarjanSCC = TarjanSCC
      self.Directed = Directed
      self.Nodes = {}

      def add_node(self,key):
      self.Nodes[str(key)] = {,'AdjacencyList':{}}

      def add_edge(self, start_node, target_node, weight = 1):
      if(str(start_node) not in self.Nodes.keys()):
      self.add_node(start_node)
      if(str(target_node) not in self.Nodes.keys()):
      self.add_node(target_node)
      self.Nodes[str(start_node)]['AdjacencyList'][str(target_node)] = {'weight' : weight}
      if not self.Directed:
      self.Nodes[str(target_node)]['AdjacencyList'][str(start_node)] = {'weight' : weight}

      def HopcroftKarp(self,u,v):
      global U,V,M,unmatched_nodesU,unmatched_nodesV

      U = set(map(str,u))
      V = set(map(str,v))
      if self.Directed:
      raise Exception("Can't compute Hopcroft Karp algorithm for a DIRECTED graph.")
      self._initializeHK()
      while True:
      AP = self._BFS_HK()
      if not AP:
      return M
      else:
      M = M ^ AP
      unmatched_nodesU = U-set([el[0] for el in M])
      unmatched_nodesV = V-set([el[1] for el in M])

      def _initializeHK(self):
      global U,V,M,unmatched_nodesU,unmatched_nodesV
      M = set()
      free_vertices = {el:True for el in V}
      for el in U:
      for node in self.Nodes[el]['AdjacencyList'].keys():
      if node in free_vertices:
      M.add((el,node))
      del free_vertices[node]
      break
      unmatched_nodesU = U-set([el[0] for el in M])
      unmatched_nodesV = V-set([el[1] for el in M])

      def _BFS_HK(self):
      global unmatched_nodesU
      global unmatched_nodesV
      global M
      global U
      global V
      vis = set()
      vis.clear()
      queue = list(copy.deepcopy(unmatched_nodesU))
      alt_g = Graph()
      while queue:
      tmp = queue.pop(0)
      vis.add(tmp)
      if tmp in U:
      for succ in self.Nodes[tmp]['AdjacencyList'].keys():
      if (tmp,succ) not in M and succ not in vis:
      alt_g.add_edge(tmp,succ)
      queue.append(succ)
      else:
      for succ in self.Nodes[tmp]['AdjacencyList'].keys():
      if (succ,tmp) in M and succ not in vis:
      alt_g.add_edge(tmp,succ)
      queue.append(succ)
      AP = self._DFS_HK(alt_g)
      if AP:
      return AP
      else:
      return None

      def _DFS_HK(self,alt_g):
      global unmatched_nodesU,visited,fathers
      fathers = {}
      fathers.clear()
      visited = set()
      visited.clear()
      queue = list(copy.deepcopy(unmatched_nodesU))
      for node in unmatched_nodesU:
      if node not in visited and node in alt_g.Nodes.keys():
      fathers[node] = None
      AP = self._DFS_HK_xplore(alt_g,node)
      if AP:
      return AP
      else:
      continue
      return None

      def _DFS_HK_xplore(self,alt_g,node):
      global U,V,M,unmatched_nodesV,fathers,visited
      visited.add(node)
      if node in unmatched_nodesV:
      AP = []
      t = node
      while t != None:
      AP.insert(0,t)
      t = fathers[t]
      return self._get_edges(AP)
      for el in alt_g.Nodes[node]['AdjacencyList'].keys():
      if el not in visited:
      fathers[el] = node
      return self._DFS_HK_xplore(alt_g,el)

      def _get_edges(self,AP):
      global U
      edges = set()
      edges.clear()
      for i in range(1,len(AP)):
      if AP[i-1] in U:
      edges.add((AP[i-1],AP[i]))
      else:
      edges.add((AP[i],AP[i-1]))
      return edges








      share







      New contributor




      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      Can some of you check what's wrong in my implementation of Hopcroft Karp algorithm to find maximum matching in a bipartite graph?



      I implemented it as a method of my Graph() class, the method input consists in two lists or set of nodes (representing the two sets of nodes of a bipartite graph).
      It seems that the code, SOMETIMES, isn't able to find an augmenting path. Sometimes instead it works, but it seems casual.



       class Graph:

      def __init__(self, TarjanSCC = False, Directed = True):
      self.TarjanSCC = TarjanSCC
      self.Directed = Directed
      self.Nodes = {}

      def add_node(self,key):
      self.Nodes[str(key)] = {,'AdjacencyList':{}}

      def add_edge(self, start_node, target_node, weight = 1):
      if(str(start_node) not in self.Nodes.keys()):
      self.add_node(start_node)
      if(str(target_node) not in self.Nodes.keys()):
      self.add_node(target_node)
      self.Nodes[str(start_node)]['AdjacencyList'][str(target_node)] = {'weight' : weight}
      if not self.Directed:
      self.Nodes[str(target_node)]['AdjacencyList'][str(start_node)] = {'weight' : weight}

      def HopcroftKarp(self,u,v):
      global U,V,M,unmatched_nodesU,unmatched_nodesV

      U = set(map(str,u))
      V = set(map(str,v))
      if self.Directed:
      raise Exception("Can't compute Hopcroft Karp algorithm for a DIRECTED graph.")
      self._initializeHK()
      while True:
      AP = self._BFS_HK()
      if not AP:
      return M
      else:
      M = M ^ AP
      unmatched_nodesU = U-set([el[0] for el in M])
      unmatched_nodesV = V-set([el[1] for el in M])

      def _initializeHK(self):
      global U,V,M,unmatched_nodesU,unmatched_nodesV
      M = set()
      free_vertices = {el:True for el in V}
      for el in U:
      for node in self.Nodes[el]['AdjacencyList'].keys():
      if node in free_vertices:
      M.add((el,node))
      del free_vertices[node]
      break
      unmatched_nodesU = U-set([el[0] for el in M])
      unmatched_nodesV = V-set([el[1] for el in M])

      def _BFS_HK(self):
      global unmatched_nodesU
      global unmatched_nodesV
      global M
      global U
      global V
      vis = set()
      vis.clear()
      queue = list(copy.deepcopy(unmatched_nodesU))
      alt_g = Graph()
      while queue:
      tmp = queue.pop(0)
      vis.add(tmp)
      if tmp in U:
      for succ in self.Nodes[tmp]['AdjacencyList'].keys():
      if (tmp,succ) not in M and succ not in vis:
      alt_g.add_edge(tmp,succ)
      queue.append(succ)
      else:
      for succ in self.Nodes[tmp]['AdjacencyList'].keys():
      if (succ,tmp) in M and succ not in vis:
      alt_g.add_edge(tmp,succ)
      queue.append(succ)
      AP = self._DFS_HK(alt_g)
      if AP:
      return AP
      else:
      return None

      def _DFS_HK(self,alt_g):
      global unmatched_nodesU,visited,fathers
      fathers = {}
      fathers.clear()
      visited = set()
      visited.clear()
      queue = list(copy.deepcopy(unmatched_nodesU))
      for node in unmatched_nodesU:
      if node not in visited and node in alt_g.Nodes.keys():
      fathers[node] = None
      AP = self._DFS_HK_xplore(alt_g,node)
      if AP:
      return AP
      else:
      continue
      return None

      def _DFS_HK_xplore(self,alt_g,node):
      global U,V,M,unmatched_nodesV,fathers,visited
      visited.add(node)
      if node in unmatched_nodesV:
      AP = []
      t = node
      while t != None:
      AP.insert(0,t)
      t = fathers[t]
      return self._get_edges(AP)
      for el in alt_g.Nodes[node]['AdjacencyList'].keys():
      if el not in visited:
      fathers[el] = node
      return self._DFS_HK_xplore(alt_g,el)

      def _get_edges(self,AP):
      global U
      edges = set()
      edges.clear()
      for i in range(1,len(AP)):
      if AP[i-1] in U:
      edges.add((AP[i-1],AP[i]))
      else:
      edges.add((AP[i],AP[i-1]))
      return edges






      python algorithm graph





      share







      New contributor




      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 mins ago









      ИванКарамазовИванКарамазов

      11




      11




      New contributor




      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      ИванКарамазов is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          ИванКарамазов is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215220%2fhopcrof-karp-algorithm-does-not-work-python3%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          ИванКарамазов is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          ИванКарамазов is a new contributor. Be nice, and check out our Code of Conduct.













          ИванКарамазов is a new contributor. Be nice, and check out our Code of Conduct.












          ИванКарамазов is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215220%2fhopcrof-karp-algorithm-does-not-work-python3%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Webac Holding Inhaltsverzeichnis Geschichte | Organisationsstruktur | Tochterfirmen |...

          What's the meaning of a knight fighting a snail in medieval book illustrations?What is the meaning of a glove...

          Salamanca Inhaltsverzeichnis Lage und Klima | Bevölkerungsentwicklung | Geschichte | Kultur und...