# Using range and dictionary in Python's Bellman-Ford implementation

The Bellman-Ford algorithm looks like this

initialize-single-source(G,s) for i = 1 to |G.V| - 1 for each edge (u,v) in G.E call Relax(u,v,w) and so on

This psuedocode index begins with 1, not zero.

Here is how I called the edge. I use dictionary for edge and vertex.

for i in range((len(self.V.keys()))-1): for vertex in self.V.keys(): for edge in self.V[vertex]:

Q1: We should begin with index zero, right?

Q2: Should we still minus 1 from the length of G.V ?

Thanks.

## Answers

Did you already give this super website a try? Sometimes answers can be found there...

Q1: We should begin with index zero, right?

Not necessarily; you could also iterate over xrange(1, len(self.V)). Starting from zero is idiomatic, though.

Q2: Should we still minus 1 from the length of G.V?

If you start counting from zero, yes. The -1 is part of the algorithm specification.

Extra advice: rewrite your snippet as

for i in xrange(len(self.V) - 1): for vertex in self.V.iterkeys(): for edge in self.V[vertex]:

to prevent building a list of keys (twice).