简体   繁体   中英

Why does my python graph class calculate the max degree incorrectly?

I am trying to calculate the max and min degrees of my Graph class in python and here is my code:

class Graph():
    def __init__(self, graph = None):
        if graph == None:
            graph = {}
        self.graph = graph
    
    def degree(self, node):
        deg =  len(self.graph[node])
        if node in self.graph[node]:
            deg += 1
        return deg

    def maxd(self):
        max = 0
        for node in self.graph:
            degree = self.degree(node)
            if degree > max:
                max = degree
        return max

    def mind(self):
        min = 10000000000
        for node in self.graph:
            nodedeg = self.degree(node)
            if nodedeg < min:
                min = nodedeg
        return min






graph = { "a" : {"c"},
          "b" : {"c", "e"},
          "c" : {"a", "b", "d", "e"},
          "d" : {"c"},
          "e" : {"c", "b"},
          "f" : {'c'}
        }

g = Graph(graph)

print("max:", g.maxd())
print("min:", g.mind())
max: 4
min: 1

the max is supposed to be 5 and I cannot figure out why it's returning 4.

You need to add the out-degree and the in-degree to get the degree of a node.

Here is an implementation:

from collections import defaultdict


class Graph():
    def __init__(self, graph=None):
        if graph == None:
            graph = {}
        self.graph = graph
        self.out_degree = defaultdict(int)
        self.in_degree = defaultdict(int)
        self.degree = defaultdict(int)

        for n in graph:
            self.out_degree[n] += 1
            for n2 in graph[n]:
                self.in_degree[n2] += 1

        for n in graph:
            self.degree[n] = self.out_degree[n] + self.in_degree[n]

    def degree(self, node):
        return self.degree[node]

    def maxd(self):
        return max(self.degree.values())

    def mind(self):
        return min(self.degree.values())


graph = {"a": {"c"},
         "b": {"c", "e"},
         "c": {"a", "b", "d", "e"},
         "d": {"c"},
         "e": {"c", "b"},
         "f": {'c'}
         }

g = Graph(graph)

print("max:", g.maxd())
print("min:", g.mind())

Outputs:

max: 6
min: 1

(the max degree is 6, not 5)

If you need to make your graph modifiable (adding nodes/edges) then you need to think about how you can modify the dictionaries that hold the node degrees, or use a different data structure.

Some additional points:

  • You shouldnt use the built-in function names min and max for variables
  • You should use float("inf") to get the maximum number:
min = -float("inf")
or
min = float("-inf")
and
max = float("inf")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM