I have this code:
import csv
from math import *
distances=[]
pos=0
tally=0
target_x=input("Please enter the X coordinate of the target city: ")
target_y=input("Please enter the Y coordinate of the target city: ")
count = sum(1 for row in csv.reader( open('cities.csv') ) )
cityname = csv.reader(open("cities.csv", "rb"))
citynames = []
citynames.extend(cityname)
cityname = []
for data in citynames:
citynames.append(data[0])
tally+=1
if tally>=count:
break
tally=0
#x coordinate list
citiesx = csv.reader(open("cities.csv", "rb"))
cities_list_x = []
cities_list_x.extend(citiesx)
cities_x = []
for data in cities_list_x:
cities_x.append(int(data[1]))
tally+=1
if tally>=count:
break
tally=0
#y coordinate list
citiesy = csv.reader(open("cities.csv", "rb"))
cities_list_y = []
cities_list_y.extend(citiesy)
cities_y = []
for data in cities_list_y:
cities_y.append(int(data[2]))
tally+=1
if tally>=count:
break
tally=0
while pos<count:
distance = (sqrt( (target_x - cities_x[pos])**2 + (target_y - cities_y[pos])**2 ))
distances.append(distance)
pos+=1
for i in range(0,count):
shortest_distance=min(distances)
closest_city=distances.index(shortest_distance)
print str(i+1)+"-"+citynames[closest_city+count],"at", round(shortest_distance,3),"units away"
del distances[distances.index(shortest_distance)]
raw_input("Press enter to exit")
When I use this spreadsheet;
city1 433 566
city2 677 788
city3 899 900
and input 678 for the first input and 789 as the second input I get this as output:
Please enter the X coordinate of the target city: 678
Please enter the Y coordinate of the target city: 789
1-city2 at 1.414 units away
2-city2 at 247.31 units away
3-city1 at 331.291 units away
Press enter to exit
When I think it should be:
"Please enter the X coordinate of the target city: 678
Please enter the Y coordinate of the target city: 789
1-city2 at 1.414 units away
2-city3 at 247.31 units away
3-city1 at 331.291 units away
Press enter to exit"
Any help is great
Thanks,
Jaro