List index out of range (Python 2.7) - python-2.7

I feel like I am constantly having this problem when I am writing a program, what I want to do is iterate over every value in my nested list and say that if it's not a zero, make it one.
Here is the error I am getting:
Traceback (most recent call last):
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
resetBoard()
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
if board[i][j] != 0:
IndexError: list index out of range
Here is my full code:
import random
grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,5,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
playerX = None
playerY = None
randX = 0
randY = 0
def getRandomGridPos():
global randX, randY
randX = int(random.uniform(0, grid[0]))
randY = int(random.uniform(0, grid[1]))
def main():
pass
def printBoard():
print str(board[0]).replace(',', '')
print str(board[1]).replace(',', '')
print str(board[2]).replace(',', '')
print str(board[3]).replace(',', '')
print str(board[4]).replace(',', '')
print str(board[5]).replace(',', '')
print str(board[6]).replace(',', '')
print str(board[7]).replace(',', '')
print str(board[8]).replace(',', '')
print str(board[9]).replace(',', '')
def resetBoard():
i = 0
j = 0
while i < 10:
if board[i][j] != 0:
board[i][j] = 0
j += 1
print "Looping"
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
print "I == 10"
else:
j += 1
resetBoard()
Can someone help me find a solution and also help me not get this error anymore (explain why it happens)?

You've already gotten several pointers to the cause of your error, but I just wanted to point out a clearer pattern to iterate multi-dimensional arrays:
for x in range(0, 10):
for y in range(0, 10):
# you will now have all values for a 10x10 array in x & y
if board[x][y] != 0:
board[x][y] = 0
If you really just want to make sure all board fields (10 x 10) are zeros, the following is even more consice:
# zero out a 10 x 10 multi-dimensional array
board = [[0] * 10] * 10

Your for reset board doesn't work for the following reasons:
"if i == 10" ,i never actually reaches 10, since it is in a while loop which states "while i < 10". The loop would exit before i actually reaches 10
no nested while loop. You need two while loops to reset the board.
When j reaches 10 this line raises an index error: if board[i][j] != 0: , because j equals 10, and the maximum index you can take of a 10 element list is 9(since index starts at 0)
I recommend reading the following
http://introtopython.org/lists_tuples.html
I would add that one of the best ways to achieve what you want in python with loops is:
for row in board: # runs the following once for every item in board
for item in row: # runs the following for every item in row.
# A second for statement is required because
# multidimensional lists are lists of lists.
if(item != 0)
item = 0 #sets items to 0 if the item isn't equal to 0

UPDATE:
Sorry but I also encoutered another problem, my bad for not checking the code:
The final code should be:
while i < 10:
if j == 10:
j = 0
i += 1
print ("J == 10")
elif board[i][j] != 0:
board[i][j] = 0
j += 1
print ("Looping")
else:
j += 1
The problem I missed was that you should have checked the j boundary before trying to access the array, only then you should start the loop again.
The problem is in this part:
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
if i = 9, j= 10 then we enter into the first if which changes i,j to be 10,10
Then the code continues and we enter the second if, thus reseting i and j making the loop go again and again...
Solve it by deleting the second if part, since the while condition will make sure we will never go to that case in the first place.

Related

List manipulation to extract values greater than current and remaining index values

I have following list:
elev = [0.0, 632.8, 629.9, 626.5, 623.7, 620.7, 620.7, 607.4, 603.2, 602.0, 606.6, 613.2, 608.4, 599.7, 583.6]
Ideally it should be in descending order but 602.0 is smaller than next 3 values (606.6,613.2,608.4) and I need a count of those values each time this issue arises. I am trying nested for loops to count those values with following:
l = len(et)
for i in xrange(1,l-1,1):
for j in xrange(1,l-1,1):
if (et[i] < et[j]):
print et[i]
But instead I get all values greater than 602.0. How do I restrict loop to only count those 3 values? Appreciate any suggestions.
I guess this will solve your problem:
l = len(et)
for i in xrange(1,l-1,1):
if et[i] < et[i+1]:
for j in xrange(i,l-1,1):
if (et[i] < et[j]):
print et[j]
It will print the values greater than your number, not all but only the ones which came after the number.
This is what I've got from my terminal:
>>> for i in xrange(1,l-1,1):
... if et[i] < et[i+1]:
... print "for",et[i]
... for j in xrange(i,l-1,1):
... if (et[i] < et[j]):
... print et[j]
...
for 602.0
606.6
613.2
608.4
for 606.6
613.2
608.4
l_elev = len(elev)
gt_cnt = 0
eq_cnt = 0
slp_idx = []
for i in xrange(1,l_elev-3,1):
# following will take care of greater than current value inversion
if elev[i+gt_cnt] < elev[i+1+gt_cnt]:
lnew = elev[i+gt_cnt:]
gt_inv = [y for y in lnew if y >= elev[i+gt_cnt]]
gt_cnt += 1
for x in xrange(i,i+len(gt_inv),1):
slp_idx.append(x)
# following will take care of adjacent equal values
if (elev[i+eq_cnt] - elev[i+eq_cnt+1]) == 0:
cnew = elev[i:]
eq_inv = [y for y in cnew if y == elev[i+eq_cnt]]
eq_cnt+=1
for y in xrange(i,i+len(eq_inv),1):
slp_idx.append(y)
# break loop to avoid out of index error
if i+gt_cnt > l_elev:
break

Sudoku code to return True or False

The procedure needs to return True or False if the given input (nxn square list of digits) conforms to sudoku or not. Given list should return True is no digit in either row or column occurs more than once
My code is producing an error right now that says:
s[i][j] == s[i][j+1]:IndexError: list index out of range
Please suggest how to fix the above issue and any other to correct this procedure
def check_sudoku(s):
i = 0
j = 0
while i<len(s):
while j<len(s):
if s[i][j] == s[i][j+1]:
return False
j = j + 1
i = i+1
while j<len(s):
while i<len(s):
if s[i][j] == s[i+1][j]:
return False
i=i+1
j=j+1
return True
j should be less than len(s)-1 because when it reaches len(s)-1 then j+1 is equal to len(s) and raises IndexError
Also I think j should be in range len(s[i])-1 not len(s)

how to change a variable name in a while loop?

I have a question. I want to use a while loop and in the while loop I have to assign a view lists, but they shouldn't be assigned to the same variable over and over again. but I don't know how much lists I have to assign.
K = 2
D = 2
while( K <= 2 or K >= 20):
K = int(raw_input("Give the number of candidates running for speaker. "))
if(K <= 2 or K >= 20):
print("Sorry, wrong input.")
while(D <= 2 or D >= 1000):
D = int(raw_input("Give the number of people who take part in the meeting. "))
if(D <= 2 or D >= 1000):
print("Sorry, wrong input.")
row = 1
vlist = [[]*D]
while(D > row):
while(K < len(vlist[row-1])):
number = int(raw_input("Give a number of a person you want to win: "))
if(0 < number < K and number not in vlist[row-1]):
vlist[row-1].append(number)
else:
print("Sorry, wrong input, try again.")
row += 1
this is what I have now, but it throws the following error: List index out of range. I don't get why...
First item of list is empty: len(vlist[0])
returns 0, so list[row-1] is trying to acces element of -1 index.

How to print only last line in a while loop

count = 0
while count ** 2 < snum_:
print "Using search with increment 1, the root lies between", count,"and", count + 1
count = count + 1
How do I get the loop to only print the last possible line?
You can try this:
count = 0
while count < 4:
print('hi')
count += 1
else:
# Replace below string with what you wish.
print('end')
+= means count + 1. else is reached after while finishes (will not print, if you break the loop instead of letting it finish normally).
With a for-loop and itertools.count():
import itertools
for count in itertools.count(1):
if count**2 >= snum_:
print "Using search with increment 1, the root lies between %d and %d" % count-1, count
break
But the general idea can also be applied to your while loop: When count**2 is no longer less than snum_, print and break.
You could save the string you want to print and print it after the loop:
count = 0
result = ''
while count ** 2 < snum_:
result = "Using search with increment 1, the root lies between %d and %d" % count, count + 1
count = count + 1
print result

Python: IndexError: list index out of range

I keep getting this error:
line 4, in timesTwo
IndexError: list index out of range
for this program:
def timesTwo(myList):
counter = 0
while (counter <= len(myList)):
if myList[counter] > 0:
myList[counter] = myList[counter]*2
counter = counter + 1
elif (myList[counter] < 0):
myList[counter] = myList[counter]*2
counter = counter + 1
else:
myList[counter] = "zero"
return myList
I'm not exactly sure how to fix the error. Any ideas?
You are setting the upper-bound of the while loop to the length of myList, which means that the final value of counter will be the length. Since lists are indexed starting at 0, this will cause an error. You can fix it by removing the = sign:
while (counter < len(myList)):
Alternatively, you could do this in a for loop that may be a bit easier to handle (not sure if this fits your use case, so the above should work if not):
def timesTwo(myList):
for index, value in enumerate(myList):
if value is not 0:
myList[index] *= 2
else:
myList[index] = 'zero'
return myList