Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading