0

I'm still learning to work with objects. I defined vertices() as a method to return the vertices (initialized as vs) in Graph. I know that there is a more concise, elegant way to write vertices() but exactly how is escaping me.

Also specifically this relates to exercise 2.5 in Think Complexity: http://greenteapress.com/complexity/html/book003.html#toc12

class Graph(dict):
    def __init__(self, vs=[], es=[]):

        for v in vs:
            self.add_vertex(v)

    def add_vertex(self, v):
        """Add a vertex to the graph."""
        self[v] = {}

    def vertices(self):
        v = []
        for i in range(len(self)):
            v.append(i)
        return v
Chris
  • 1,090
  • 2
  • 11
  • 22

2 Answers2

1

You can make it one line with a list comprehension:

def vertices(self):
    return [i for i in range(len(self))]
Odoood
  • 11
  • 1
1

I defined vertices() as a method to return the vertices (initialized as vs) in Graph.

As vs in __init__ contains keys of the dict, i guess this is what you want.

    def vertices(self):
        return self.keys()

If so, you don't need vertices method at all - just always use Graph.keys()

warvariuc
  • 57,116
  • 41
  • 173
  • 227