Reputation: 79
So I have code with two functions. The first one prints an empty 20x20 board and the second one prints a word in the middle. Now I'm trying to write a function that checks if an input word will intersect with another word at the same letter (like crossword). This is the code for the first two functions(it works no changes needed here):
blank = ' '
board = [[' '] * 20 for i in range(20)]
def printboard(board):
columns = '01234567890123456789'
rows = '_' * 20
print(' ' + columns)
print(' ' + rows)
for i in range(20):
s = ''.join(board[i])
print('|' + s +'|' + str(i))
print(' ' + rows)
print(' ' + columns)
def addFirstWord(board, word):
n = len(word)
if n > 20:
return False
row = 10
col = (20 - n) // 2
board[row][col:col+n] = word
return True
addFirstWord(board, 'hippopotamus')
And this is what I've tried so far,but it only checks 1st position with 1st letter etc..
def checkvertical(board, word, row, col):
n = len(word)
if n > 20: #checks if word is larger than board
return False
for i in range (len(word)):
if board[row+i][col] == word[i]:
return True
else:
return False
print(checkvertical(board, 'horse', 10, 15))
printboard(board)
What I want is a function to check if a word that's printed vertically will properly intersect with an existing word on the board when it's printed starting at a specific row and column and going downwards.
Upvotes: 2
Views: 114
Reputation: 14546
This should work:
def checkvertical(board, word, row, col):
intersects = False
n = len(word)
if n > 20: #checks if word is larger than board
return False
for i, c in enumerate(word):
if board[row+i][col] not in [' ', word[i]]:
return False
elif board[row+i][col] == word[i]:
intersects = True
return intersects
Gives:
>>> print(checkvertical(board, 'horse', 7, 14))
False
>>> print(checkvertical(board, 'horse', 7, 15))
True
>>> print(checkvertical(board, 'horse', 10, 4))
True
Basically, we loop over the word using enumerate and check that the place we want to put that piece either holds the same letter or is blank. If we never find a place where that is the case, we return True.
Upvotes: 2