My Python code is throwing an exception here on this line, giving a "list index out of range" error, but I cannot find which part of my code is making i or r out of the array's range.
import time
import random
import math
sudoLine = [0,0,0]
possibleNums = [1,2,3]
print(len(possibleNums))
length = len(possibleNums) - 1
for i in range(3):
r = random.randint(0,length)
sudoLine[i] = possibleNums[r]
possibleNums.pop(r)
print(sudoLine)
The error message is as follows:
Message=list index out of range
Source=C:\Users\heyma\source\repos\Sudoku Solver\Sudoku Solver\Sudoku_Solver.py
StackTrace:
File "C:\Users\heyma\source\repos\Sudoku Solver\Sudoku Solver\Sudoku_Solver.py", line 18, in <module> (Current frame)
sudoLine[i] = possibleNums[r]
Sorry if this is a bad question, I'm fairly new as this is my first project!
CodePudding user response:
The issue is that the length of possibleNums is decreasing with every iteration of the for-loop but you only calculate the length variable once (before the loop). Move the line length = len(possibleNums) - 1 inside the for-loop:
import time
import random
import math
sudoLine = [0,0,0]
possibleNums = [1,2,3]
print(len(possibleNums))
for i in range(3):
length = len(possibleNums) - 1
r = random.randint(0,length)
sudoLine[i] = possibleNums[r]
possibleNums.pop(r)
print(sudoLine)
CodePudding user response:
The pop method removes an element from a list. So your possibleNums list is getting shorter with each iteration.
So at some point the value of r might be chosen to be greater that the current length of possibleNums.
CodePudding user response:
This error is thrown because the length of the possibleNums list changed after pop command was issued. Therefore reducing the number of indexes.
import random
sudoLine = [0,0,0]
possible_nums = [1,2,3]
i = 0
while len(possible_nums) > 0:
length = len(possible_nums) - 1
r = random.randint(0, length)
sudoLine[i] = possible_nums[r]
possible_nums.pop(r)
i = 1
print(sudoLine)
