Python code - List index out of range? -
for assigment, have travelling salesman sort of code using geolocator code list of cities not given us, assuming first city in list starting/ending city.
my code incomplete, barely, think have left take distance sec lastly initial city.
anyways, maintain running "list index out of range" problem when trying take distance between 2 cities in list.
i think i've made if/else statement force indices out of range, still error. i'm reasonably new python, please excuse poor structure/syntax. imports have mandatory project, again, please don't judge. error may stupid , obvious, if is, i'm having problem 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 hope
edit: traceback, , cutting out unnecessary code:
traceback (most recent phone 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
i'm not sure how supposed working, here's pretty clear:
you maintain callingcitylist.pop()
, , never add together it, it's getting smaller. you maintain doing p += 1
, , never cut down or reset other value, it's getting larger. you don't exit until citylist
downwards 1 city. every time through loop, look involving citylist[p]
. so, assuming p
ever gets 2 or higher (which seems will), you're guaranteed nail point citylist
has less p
elements, next citylist[p]
raise indexerror
.
most problem you're supposed reducing or resetting p
somewhere, never are. if had guess, i'd guess when citylist.pop(int(cityat))
, if p >= cityat
need p -= 1
. since can't understand code supposed doing, can't sure of that.
python list indexing range out
No comments:
Post a Comment