Saturday, 15 January 2011

arrays - Break Loop if Index is Out Of Bounds of While Loop in Python -



arrays - Break Loop if Index is Out Of Bounds of While Loop in Python -

i have while loop looks this:

while a[xp][yp] - a[xp-1][yp] == 0 , a[xp][yp] - a[xp+1][yp] == 0 , a[xp][yp] - a[xp][yp-1] == 0 , a[xp][yp] - a[xp][yp+1] == 0: c=randint(0,3) if c==0: xp=xp+1; yp=yp elif c==1: xp=xp-1; yp=yp elif c==2: xp=xp; yp=yp+1 else: xp=xp; yp=yp-1 xp=xp; yp=yp

the problem if xp or yp = 0 or n (the length of array in either x direction or y, square matrix), conditions in while loop break downwards , out of bounds error. new set of coordinates if xp=0 or xp=n or yp=0 or yp=n (i have separate piece of code this) , allow while loop run again.

the nature of code seems 1 in every 4 times code runs without going out of bounds. need maintain running until happens work.

you check if operation force index out of bounds, so:

if c==0 , xp < len(a)-1: xp += 1 elif c==1 , xp > 0: xp -= 1 # etc...

this create sure xp stays in bounds before changing it, rather looking @ afterwards.

the sec problem in while statement - if create sure xp , yp in bounds array, checking outside in initial condition:

while a[xp][yp] - a[xp-1][yp] == 0 , a[xp][yp] - a[xp+1][yp] == 0 \ , a[xp][yp] - a[xp][yp-1] == 0 , a[xp][yp] - a[xp][yp+1] == 0:

here, i'll assume a has size of 10 10 (indexes 0 9). if set xp 0 , yp 9, work out to:

while a[0][9] - a[-1][9] == 0 , a[0][9] - a[1][9] == 0 \ a[0][9] - a[0][10] == 0 , a[0][9] - a[0][10]:

a[10] throw out of bounds error, you'll have determine how alter loop when index right on boundaries of array. note a[9] still valid index array - it's checking next index problem.

as aside, a[-1] won't throw exception, although it's logic error - the negative index access final element in array.

a possible way prepare it, although it's dependent on need do: python short-circuit or operator, possible write without throwing exception:

while (xp <= len(a)-2 or a[xp][yp]-a[xp+1][yp] == 0) , \ (xp > 1 or a[xp][yp]-a[xp-1][yp] == 0) , #etc...

here, if xp less len(a)-2 (the first clause evaluates true), other half of or statement won't evaluated, out of bounds exception won't occur, , loop go on run (as long xp greater 1, , rest of statement evaluates true).

python arrays matrix while-loop indexoutofboundsexception

No comments:

Post a Comment