Reputation: 159
Hi I'm trying to write a program that allows the user to enter a trip as a sequence of any number of map references on one line, and reports the total length of the trip, assuming they can travel in straight lines.
The desired output is
Enter Trip Map References: E6 E4 D7 d43 F5
Bad reference: d43
0r
Enter Trip Map References: C2 B5 Y25
Total distance = 16.8km
so far my current code is :
dict = {}
n = input("Enter trip map references: ") . split()
print (n)
for i in n:
if i.isupper()==False:
print("Bad reference: ",i)
else:
i = i.lower()
for character.isalpha() == True:
number = ord(character) -96
character = character.upper()
dict[character] = number
print(dict)
for i in n:
x = i[0]
y = i[1]
if x in dict:
i = (dict[x],int(y))
My problem is I'm stuck having to select each coordinate and execute Pythagora's formula (sqrt((x2-x1)^2+(y2-y1)^2) for the 2 of the coordinates. The Pythagora's formula should execute starting between the first 2 coordinates, then 2nd and 3rd and then 3rd and 4th, and so on.
How can I achieve this?
Upvotes: 0
Views: 85
Reputation: 17344
You can calculate the formula like this:
from math import sqrt
point1 = (0,0)
point2 = (1,1)
result = (sqrt(point2[0] - point1[0]))**2 + (sqrt(point2[1]-point1[1]))**2
So a kind of abstract example would be.
points = [p1,p2,p3,p4]
for i in range(1,len(points)):
j = i - 1
p1 = points[i]
p2 = points[j]
result = (sqrt(p2[0] - p1[0]))**2 + (sqrt(p2[1]-p1[1]))**2
You could also try the hypot
function in the math module as suggested by Ture Pålsson
Upvotes: 1