For an assigment, we have to do a travelling salesman sort of code using geolocator code from a list of cities that is not given to us, assuming the first city in the list is the starting/ending city.
My code is incomplete, but barely, as I think all I have left to do is take the distance from the second to last to the initial city.
Anyways, I keep running into a "list index out of range" problem when trying to take the distance between two cities in the list.
I think I've made an if/else statement for everything that could push my indices out of range, but I still get the error. I'm reasonably new to Python, so please excuse my poor structure/syntax. The imports I have are mandatory for this project, so again, please don't judge. The mistake may be really stupid and obvious, but if it is, I'm having trouble seeing it.
#!/usr/bin/env python
cityfile = open(sys.argv[1], "r")
citylistwithn = cityfile.readlines()
citylist = list(map(lambda each:each.strip('\n'), citylistwithn))
initcity = 0
def main():
p = 0
distancebetweencities = 1
totaldistance = 0
cityat = 0
while len(citylist) >= 1:
currentdistance = vincenty(citycoords(citylist[cityat]), citycoords(citylist[p])).miles
if currentdistance > distancebetweencities:
distancebetweencities = currentdistance
if int(p) < len(citylist)-1:
p += 1
else:
p = p
elif currentdistance < distancebetweencities:
distancebetweencities = distancebetweencities
if int(p) < len(citylist)-1:
p += 1
else:
p = p
elif currentdistance == distancebetweencities:
totaldistance += distancebetweencities
citylist.pop(int(cityat))
if int(p) >= 1:
cityat = int(p) - 1
else:
cityat = int(p)
print(totaldistance)
main()
Please help me stackoverflow, you're my only hope
EDIT: Traceback, and cut out some unnecessary code:
Traceback (most recent call last):
File "/home/user/assignment6.py", line 43, in <module>
main()
File "/home/user/assignment6.py", line 22, in main
currentdistance = vincenty(citycoords(citylist[cityat]), citycoords(citylist[p])).miles
IndexError: list index out of range