calculate distance of a path


I am trying to calculate the distance of a path when the distances are given like this:
AB = 8, AC = 4, AD = 8, AE = 11, BC = 5, BD = 6 , BE = 3, etc
So if the path followed is ABE, the total distance will be 8 + 3 =11.

I tried the following code:

'dictionaries with paths and distances 
distances = {"AB" : 8, "AC" : 4, "AD" :  8, "AE" : 11, "BC" : 5, "BD" : 6 , "BE" : 3}

'calculation path ABE
path = "AB-BE"
distance = 0 

for character in path:
   for key, value in distances.items():
      if key == path:
         distance = distance + value

print (distance)

but my distance remains 0.

What am I doing wrong?

>Solution :

When you do for character in path: you iterate the string path char by char. That means that in the first iteration, the value of character is A and not AB. Additionally, since the keys of distances are 2-grans none of them will be equal to path. That is key == path will never be True.

I suggest splitting path and then iterating them over:

path_splits = path.split("-")
distance = 0
for path_split in path_splits:
   distance +=distances[path_split]

print (distance)

If path_split does not exist in distances an error will occur but that a good sign to check either the path or the distances

Leave a ReplyCancel reply