I'm getting the IndexError on line 50 (the sixth line of checkForDisallowedCharacters while j < len(resultSet[i]):)
I get this error when I input '***er', 't', and 'canpilru' into the console when prompted
Using my print statements I've found that this error occurs when the resultSet array has a length of 141, and when i is 0
resultSet[0] is 'paper' and it clearly exists
If anyone can explain why this is throwing an error I would be very grateful
import csv
import os
import sys
def buildDictionary():
dictionary = []
with open("./wordle-helper/wordle-dictionary.csv", newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
dictionary.append(row)
for i in range(len(dictionary)):
dictionary[i] = dictionary[i][0].lower()
return dictionary
def buildTestWordComposition(testWord):
testWordComposition = []
for i in range(len(testWord)):
if testWord[i] == "*":
testWordComposition.append(i)
return testWordComposition
def buildThreshold(testWord):
threshold = 0
for character in testWord:
if character != "*":
threshold += 1
return threshold
def checkForSoftMatches(dictionary, testWord, threshold):
resultSet = []
for word in dictionary:
testThreshold = 0
for i in range(5):
if testWord[i] == "*":
continue
elif testWord[i] == word[i]:
testThreshold += 1
if testThreshold == threshold:
resultSet.append(word)
return resultSet
def checkForDisallowedCharacters(resultSet, disallowedCharacters):
i = 0
while i < len(resultSet):
print(len(resultSet), i, resultSet[i][0])
j = 0
while j < len(resultSet[i]):
for character in disallowedCharacters:
if resultSet[i][j] == character:
try:
resultSet.remove(resultSet[i])
finally:
i -= 1
j = -1
break
j += 1
i += 1
if i < 0:
i = 0
elif i >= len(resultSet):
break
return resultSet
def checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition):
resultSetChecked = []
threshold = len(requiredCharacters)
m = 0
resultSetCheckedLength = 0
while m < len(resultSetNoDisallowedCharacters):
compareToThreshold = 0
for aCharacter in requiredCharacters:
for number in testWordComposition:
if resultSetNoDisallowedCharacters[m][number] == aCharacter:
compareToThreshold += 1
break
if len(resultSetChecked) != resultSetCheckedLength:
break
if compareToThreshold == threshold:
resultSetChecked.append(resultSetNoDisallowedCharacters[m])
resultSetCheckedLength = len(resultSetChecked)
m += 1
return resultSetChecked
def wordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
dictionary = buildDictionary()
testWordComposition = buildTestWordComposition(testWord)
threshold = buildThreshold(testWord)
resultSet = checkForSoftMatches(dictionary, testWord, threshold)
resultSetNoDisallowedCharacters = checkForDisallowedCharacters(resultSet, disallowedCharacters)
resultSetChecked = checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition)
if not resultSetChecked:
return resultSetNoDisallowedCharacters
return resultSetChecked
def printWordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
print("All possible words are listed below\n\n-----------------------------------------------\n")
for word in wordleHelper(testWord, requiredCharacters, disallowedCharacters):
print(word)
def handlePersistentCharacters(disallowedCharactersComplete):
willDisallowedCharactersPersist = input("Would you like to continue using your previous list of grey letters? (y/n): ")
if willDisallowedCharactersPersist == "y":
return disallowedCharactersComplete
elif willDisallowedCharactersPersist == "n":
return []
else:
print("Please enter a valid character")
handlePersistentCharacters(disallowedCharactersComplete)
def clearConsole():
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
os.system('clear')
elif sys.platform.startswith('win'):
os.system('cls')
def buildParsed(unparsed):
parsed = []
for letter in unparsed:
parsed.append(letter)
return parsed
def handleUserContinue(disallowedCharactersComplete):
willUserContinue = input("Would you like to use World Helper (tm) again? (y/n): ")
if willUserContinue == "n":
sys.exit()
persistentDisallowedCharacters = handlePersistentCharacters(disallowedCharactersComplete)
if willUserContinue == "y":
promptUser(persistentDisallowedCharacters)
def promptUser(persistentDisallowedCharacters=[]):
clearConsole()
testWord = input("Please enter your Wordle guess in the form of *la*t where 'l', 'a', and 't' are the green letters from your guess, and the '*'s are yellow or grey letters from your guess: ")
requiredCharacters = input("Please enter your letters in yellow here in the form of 'abcxyz' (do not enter letters which are already in your Wordle guess string): ")
disallowedCharacters = input("Please enter your letters in grey here (in the form of 'abcxyz'): ")
requiredCharactersParsed = buildParsed(requiredCharacters)
disallowedCharactersParsed = buildParsed(disallowedCharacters)
disallowedCharactersComplete = persistentDisallowedCharacters + disallowedCharactersParsed
printWordleHelper(testWord, requiredCharactersParsed, disallowedCharactersComplete)
handleUserContinue(disallowedCharactersComplete)
promptUser()
what‘s the problem with my code and how can I fix it.
The problems are in lines:
world[r].append(element)
world = createWorld()
world = createWorld()
Now I show all of the code, but it seems too long need more text to make it available to post, so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.so ignore this part.
This was the error given:
IndexError: list index out of range
There are more details in the code below, appreciate it if you can help:)
import random
SIZE = 4
EMPTY = " "
PERSON = "P"
PET = "T"
POOP = "O"
ERROR = "!"
CLEANED = "."
MAX_RANDOM = 10
def clean(world, endRow, endColumn):
print("Scooping the poop")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == POOP:
world[r][c] = CLEANED
def count(world, endRow, endColumn):
print("Counting number of occurances of a character")
number = 0
element = input("Enter character: ")
for r in range(SIZE):
for c in range(SIZE):
if world[r][c] == element:
number += 1
return(element, number)
def createElement():
tempNum = random.randrange(MAX_RANDOM)+1
if ((tempNum >= 1) and (tempNum <= 5)):
tempElement = EMPTY
elif ((tempNum >= 6) and (tempNum <= 7)):
tempElement = PERSON
elif (tempNum == 8):
tempElement = PET
elif ((tempNum >= 9) and (tempNum <= 10)):
tempElement = POOP
else:
tempElement = ERROR
return(tempElement)
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return(world)
def display(world):
print("OUR WORLD")
print("========")
r = 0
while (r < SIZE):
c = 0
while (c < SIZE):
print(world[r][c], end="")
c = c + 1
print()
r = r + 1
print("========\n")
def getEndPoint():
endRow = int(input("Enter the row: "))
while not 0 <= endRow <= 3:
print("Invalid input. Row value should be in range 0-3")
endRow = int(input("Enter the row: "))
endColumn = int(input("Enter the column: "))
while not 0 <= endColumn <= 3:
print("Invalid input. Column value should be in range 0-3")
endColumn = int(input("Enter the column: "))
return (endRow, endColumn)
def start():
world = createWorld()
display(world)
endRow, endColumn = getEndPoint()
element, number = count(world, endRow, endColumn)
print("# occurances of %s=%d" % (element, number))
clean(world, endRow, endColumn)
display(world)
start()
You need to update the r value in the outer loop, currently it is being updated in the inner loop.
def createWorld():
world = []
r = 0
while (r < SIZE):
world.append([])
c = 0
while (c < SIZE):
element = createElement()
world[r].append(element)
c = c + 1
r = r + 1
return (world)
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. I have solved this program earlier, but am trying to rework my code to mirror that which I used to fashion a sudoku solver. I cannot seem to find the logical error but when I run the code, nothing prints. My program is attached below and if anyone could find my error that would be very helpful!
import numpy as np
def main():
global n
n = input("Enter N")
n = int(n)
global board
board = np.zeros((n,n), dtype=int)
solve_board()
def solve_board():
for row in range(n):
for col in range(n):
if board[row][col] == 0: #no queen
if (is_valid (board,row,col,n)):
board[row][col] = 1 #Assigning 1 for queen
solve_board()
board[row][col] = 0
return False
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
def is_valid(board,i,j,n):
if 1 in board[i]: #Checking row
return False
for row in range(0,i): #Checking column
if (board[row][j]==1):
return False
x,y = i,j
while (x>=0 and y>=0): #left diagonal
if (board[x][y]==1):
return False
x-=1
y-=1
x,y = i,j
while (x>=0 and y<n): #right diagonal
if (board[x][y]==1):
return False
x-=1
y+=1
return True
if __name__ == "__main__":
main()
This is how I had solved this code earlier, with solve_board being altered as followed.
def solve_board(row):
if(row == n):
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
print("")
else:
for col in range(n):
if (is_valid (board,row,col,n)):
board[row][col]=1
solve_board(row+1)
board[row][col] = 0
return False
Here is where the inspiration for my current code came from, a sudoku solver that I designed where I used 2 nested for loops; one for rows and one for columns. Based on this I had altered my solve_board(row) in my original n-queens code to the current function without a parameter. This sudoku code works perfectly.
def solve_board():
global board
for rowno in range(9):
#print ("row",rowno)
for colno in range(9):
#print("col",colno)
if board[rowno][colno] == 0:
for i in range(1,10):
#print(i)
if (is_valid(board,rowno,colno,i)):
board[rowno][colno]=i
solve_board()
board[rowno][colno]=0
return False
print (np.matrix(board))
I think the issue might lie in the fact that in the N-Queens problem the board does not fill up, i.e there are still 0s while for sudoku the entire board fills up and therefore when the ''if board[row][col] == 0'' is proven false exits the loop and prints. In the N-Queens problem since zero's are always present, it becomes an issue.
Try this
import numpy as np
def main():
global n
n = input("Enter N: ")
n = int(n)
global board
board = np.zeros((n,n), dtype=int)
solve_board()
def print_board():
print('-'*n)
for row in board:
for col in row:
if col == 1:
print ("Q", end = " ")
else:
print (".", end = " ")
print()
def is_valid(board,i,j,n):
if 1 in board[i]: #Checking row
return False
for row in range(0, n): #Checking column
if (board[row][j]==1):
return False
for k in range(0,n):
for l in range(0,n):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return False
return True
def solve_board():
for row in range(n):
for col in range(n):
if board[row][col] == 0: #no queen
if (is_valid (board,row,col,n)):
board[row][col] = 1 #Assigning 1 for queen
if np.count_nonzero(board) == n:
print_board()
return True
solve_board()
board[row][col] = 0
else:
return False
if __name__ == "__main__":
main()
I'm working on a connect4 and I have an issue on the piece slide down part.
When I launch the game, the pieces stacked themself only once like that.
000000
000000
000000
000000
000000
PP0000
XX0000
But after that, it doesn't stack anymore. If the user chose to put a piece on the first or second row it won't stack the piece over the actual one. I tried to figure out where the issue was coming from but I don't see it and beeing new in python doesn't help a lot.
board = []
for x in range(0, 7):
board.append(["O"] * 6)
def print_board(board):
for row in board:
print(" ".join(row))
def user_one(board):
status = 0
clm = 0
first_x = int(input("Enter a Row: "))
for i in board:
while i == "0":
clm += 1
if board[clm - 1][first_x - 1] == "P":
board[clm - 2][first_x - 1] = "X"
else:
board[clm - 1][first_x - 1] = "X"
status = 1
print_board(board)
def user_two(board):
status = 0
clm = 0
second_p = int(input("Enter a Row: "))
for i in board:
while i == "0":
clm += 1
if board[clm - 1][second_p - 1] == "X":
board[clm - 2][second_p - 1] = "P"
else:
board[clm - 1][second_p - 1] = "P"
status = 2
print_board(board)
def launch_game(board):
while True:
user_one(board)
user_two(board)
launch_game(board)
I think overall was a bit of confusion between column and row. I took your code and modified it a little bit. So this should work:
board = []
for x in range(0, 7):
board.append(["O"] * 6)
def print_board(board):
for row in board:
print(" ".join(row))
def user_one(board):
clm = 0
selected_column = int(input("Enter a column: "))
for i in reversed(range(len(board))):
if board[i][selected_column-1] == "O":
board[i][selected_column-1] = "X"
break
print_board(board)
def user_two(board):
clm = 0
selected_column = int(input("Enter a column: "))
for i in reversed(range(len(board))):
if board[i][selected_column-1] == "O":
board[i][selected_column-1] = "P"
break
print_board(board)
def launch_game(board):
while True:
user_one(board)
user_two(board)
launch_game(board)
You can still improve on removing unused variables, names and refactoring the functions (so that you only have one for your piece slide down).
I am currently working on a connect 4 game in python and I was hoping to allow the player to customise the board (be able to choose the size of the board. However when I try to add this in it breaks my code. Is there any way around this? Or will I just have to hard code the board size in?
def CreateBoard(r, c, b, n):
for i in range(1,(r+1)):
n.append(str(i))
b.append(n)
for i in range(c):
b.append(['*']*(r))
return(b)
def printBoard(b):
for lst in b:
print(" ".join(lst))
return b
def check(board, n):
n = []
for i in range(1,len(board[1])+1):
if board[1][i-1] == '*':
n.append(i)
print(n)
user = (input('Enter column: '))
if(user.isdigit() == True):
user = int(user)
if (user in n):
return(user)
print('Invalid input')
return check(board, n)
def WinningCon(b, r, u, c):
'row'
loop1 = True
rowCon = ""
colCon = ""
for i in range(0,len(b[1])):
rowCon += b[r][i]
if('X'*4 in rowCon) or('O'*4 in rowCon):
return(True)
for i in range(1,c+1):
colCon += b[i][u-1]
if('X'*4 in colCon) or('O'*4 in colCon):
return(True)
def Diag2(u, r, b, row, column):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
if(rtemp1 == 1):
break
elif(utemp1 == column):
break
rtemp1 -= 1
utemp1 += 1
while(True):
if(rtemp2 == row-1):
break
elif(utemp2 == 0):
break
rtemp2 +=1
utemp2 -=1
end += b[rtemp2][utemp2]
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def Diag1(u, r, b, row, column):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
if(rtemp1 == 1):
break
elif(utemp1 == 0):
break
rtemp1 -= 1
utemp1 -= 1
while(True):
if(rtemp2 == row-1):
break
elif(utemp2 == column):
break
rtemp2 +=1
utemp2 +=1
end += b[rtemp2][utemp2]
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def ProcessInput(u, s, b, r):
rowNum = r-1
u = u-1
while(not b[rowNum][u] == '*'):
rowNum -= 1
b[rowNum][u] = s
return(rowNum)
def EndGame(g, b, p):
printBoard(b)
print("Congrats %s, you've won!" %p)
replayGame = input('Would you like to play again? Yes or No?\n').lower()
if replayGame == 'yes':
MainGame()
else:
g = False
return(g)
def MainGame():
row = 7 #input('Enter number of rows')
column = 6 #input('Enter number of columns')
board = []
nums = []
board = CreateBoard(row, column, board, nums)
player1 = 'K'#input('Enter name: ')
player2 = 'A'#input('Enter name: ')
turn = 1
GameOn = True
while(GameOn):
board = printBoard(board)
if(not turn%2 == 0):
print("It's %s's turn" %player1)
user = check(board, nums)
rc = ProcessInput(user, "X", board, row)
if(WinningCon(board, rc , user, column) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag1(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag2(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player1)
else:
print("It's %s's turn" %player2)
user = check(board, nums)
rc = ProcessInput(user, "O", board, row)
if(WinningCon(board, rc , user, column) == True):
GameOn = EndGame(GameOn, board, player2)
elif(Diag1(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player2)
elif(Diag2(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player2)
turn +=1
MainGame()
An example of an error message it throws up:
Enter number of columns4
Enter number of rows5
1 2 3 4
* * * *
* * * *
* * * *
* * * *
* * * *
It's K's turn
[1, 2, 3, 4]
Enter column: 4
Traceback (most recent call last):
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 169, in <module>
MainGame()
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 150, in MainGame
GameOn = EndGame(GameOn, board, player1)
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 127, in EndGame
MainGame()
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 153, in MainGame
elif(Diag2(user, rc, board, row, column) == True):
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 66, in Diag2
beg += b[rtemp1][utemp1]
IndexError: list index out of range
def CreateBoard(r, c, b, n):
for i in range(1,(r+1)):
n.append(str(i))
b.append(n)
for i in range(c):
b.append(['*']*(r))
return(b)
def printBoard(b):
for lst in b:
print(" ".join(lst))
return b
def check(board, n):
n = []
for i in range(1,len(board[1])+1):
if board[1][i-1] == '*':
n.append(i)
print(n)
user = (input('Enter column: '))
if(user.isdigit() == True):
user = int(user)
if (user in n):
return(user)
print('Invalid input')
return check(board, n)
def WinningCon(b, r, u, c):
loop1 = True
rowCon = ""
colCon = ""
for i in range(0,len(b[1])):
rowCon += b[r][i]
if('X'*4 in rowCon) or('O'*4 in rowCon):
return(True)
for i in range(1,c+1):
colCon += b[i][u-1]
if('X'*4 in colCon) or('O'*4 in colCon):
return(True)
def Diag2(u, r, b, column, row):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
rtemp1 -= 1
utemp1 += 1
if(rtemp1 == 1):
break
elif(utemp1 >= column - 1):
break
while(True):
end += b[rtemp2][utemp2]
rtemp2 +=1
utemp2 -=1
if(rtemp2 >= row):
break
elif(utemp2 == 0):
break
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def Diag1(u, r, b, column, row):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
rtemp1 -= 1
utemp1 -= 1
if(rtemp1 == 1):
break
elif(utemp1 == 0):
break
while(True):
print('Row ' + str(rtemp2))
print('Colum ' +str(utemp2))
end += b[rtemp2][utemp2]
rtemp2 +=1
utemp2 +=1
if(rtemp2 >= row):
break
elif(utemp2 >= column-1):
break
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def ProcessInput(u, s, b, r):
rowNum = r
u = u-1
print('Row: ' + str(rowNum))
print('Col: ' + str(u))
while(not b[rowNum][u] == '*'):
rowNum -= 1
print('New Row Num: ' + str(rowNum))
b[rowNum][u] = s
printBoard(b)
return(rowNum)
def EndGame(g, b, p):
printBoard(b)
print("Congrats %s, you've won!" %p)
replayGame = input('Would you like to play again? Yes or No?\n').lower()
if replayGame == 'yes':
MainGame()
else:
g = False
return(g)
def MainGame():
column = int(input('Enter number of columns'))
row = int(input('Enter number of rows'))
board = []
nums = []
board = CreateBoard(column, row, board, nums)
player1 = 'K'#input('Enter name: ')
player2 = 'A'#input('Enter name: ')
turn = 1
GameOn = True
while(GameOn):
board = printBoard(board)
user = check(board, nums)
if(turn%2 != 0):
print("It's %s's turn" %player1)
rc = ProcessInput(user, "X", board, row)
else:
print("It's %s's turn" %player2)
rc = ProcessInput(user, "O", board, row)
if(WinningCon(board, rc , user, row) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag1(user, rc, board, column, row) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag2(user, rc, board, column, row) == True):
GameOn = EndGame(GameOn, board, player1)
turn +=1
MainGame()