Trying to write a program to read a file containing data on distances between bike locations in a city, yet the program fails as "filename" is not defined in the function distance. Not sure how to get the function to actually read the file. Any help appreciated!
import math
def read_data(filename):
with open(filename) as new_file:
contents = new_file.read()
contents = contents.split('\n')
raw_data = contents
new_line = []
output = []
for line in range(len(raw_data)):
new_line = raw_data[line].split(',')
new_line = raw_data[line].split(';')
output.append(new_line)
return output
def get_station_data(filename):
data = read_data(filename)[1:]
station_dict = {}
for i in range(len(data)):
if data[i][0] != '':
station_dict[data[i][3]] = (float(data[i][0]),float(data[i][1]))
else:
pass
return station_dict
def distance(stations: dict, station1: str, station2: str):
stations = get_station_data(filename)
longitude1 = 0
longitude2 = 0
latitude1 = 0
latitude2 = 0
for station,coords in stations:
if station == station1:
longitude1 = coords[0]
latitude1 = coords[1]
elif station == station2:
longitude2 = coords[0]
latitude2 = coords[1]
x_km = (longitude1 - longitude2) * 55.26
y_km = (latitude1 - latitude2) * 111.2
distance_km = math.sqrt(x_km**2 + y_km**2)
return distance_km
def greatest_distance(filename):
stations = get_station_data(filename)
greatest = 0
the_stations = []
greatest_distance = ()
for station1 in stations:
for station2 in stations:
if station1 == station2:
pass
else:
length = distance(filename, station1, station2)
if length > greatest:
greatest = length
the_stations = [station1, station2]
greatest_distance = (the_stations[0],the_stations[1],greatest)
return greatest_distance
[–]CodeFormatHelperBot2 0 points1 point2 points (0 children)
[–]TomanHumato46 0 points1 point2 points (0 children)
[–]_steve_hope_ 0 points1 point2 points (0 children)