April 2nd, 2005, 04:25 PM
List index range:easy but I can't see it
I'm stumped. I've ran this with a least 100 little changes and I can't figure out why I keep going out of range (and yes, Grim Archon, I have been doing my reading ). This uses a robot class that isn't published, so I don't know if anyone can help me by just looking at the syntax? This is the pertinent code I have, and what I get when I run it (please excuse the scaffolding):
direction=[N,W,E,S] #4 robot directions possible/scannable
xN,yN=r.sensor(N) #objects and how far away they are
for (i) in objlist:
#print type (m)
for j in range(m): <--m is type 'int', m=2
I figured this would work just like any other time I've used the range function, but it's not! Notice the j index keeps reinitializing itself to 0 (from the scaffolding):
Traceback (most recent call last):
File "C:\WINDOWS\Desktop\a8backup\samprobot.py", line 27, in ?
r.move(direction[m]) <--m is type 'int', m=2
File "robotlib.py", line 451, in move
RuntimeError: Past edge of board
I know this has to have a simple answer, but I can't find it. If anyone can point me in the right direction I sure would appreciate it!
April 2nd, 2005, 05:01 PM
When you use "for j in range(m)", you do not need to increment j, i.e. you don't need the j = j+1 line in there. Python takes care of that automatically. What is going on in your program is this...
The for j in range(m) line constructs a list that looks like this when m=2: [0,1].
j is 0 the first time through the loop, and prints as such.
You incrment j.
Python increments j (so it is now 2).
You are now out of your range, and the loop exits.
By the way, your code would be much easier to read if you used code tags.
hope this helps.
April 2nd, 2005, 05:39 PM
The never ending loop
Actually I figured out what the main problem is: the line above the 'j range' line is a loop in the IF statement ABOVE it: the loop doesn't END (that's the problem), it keeps cycling through the IF statement:
I need to keep that 'if' statement and find a way to only loop through the indexing on the line below it. Any ideas? I know this is simple, but I've spent so long looking at it....
And I'm sorry but I don't know what code tags are.
Originally Posted by Zone
April 2nd, 2005, 06:28 PM
Oops... I made a mistake when I said that python will re-increment j. It won't. It will just set j to the next item in the range, and disregard your j = j+ 1 statement. In other words, j=j+1 is not needed, but it is not your problem either.
Code tags are used to preserve indentation (crucial for python). You get them by using the little "wrap in code tags" button on the form for submitting a thread.
April 2nd, 2005, 06:47 PM
I *finally* figured out what the problem was; thanks for pointing out the icons, I haven't even really noticed they were there.
Originally Posted by Zone