Reputation: 79
I'm writing code that creates a crossword and I want code that finds a specific char in a table. so for example if the board contains the word 'car' and I'm looking for the char 'a', it would return the value for the row and column. This is the code I have for printing the board and the first word.
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, 'car')
printboard(board)
I think I have to write a loop that checks every index in the board but i'm not sure how to write it. Thanks
Upvotes: 2
Views: 560
Reputation: 14486
This should work:
def findCharacter(board, char):
# Loop through all rows and columns
for i, c in enumerate(board):
for j, r in enumerate(c):
# If we find the character, return it
if r == char:
return j, i
For example:
>>> board = [[' '] * 20 for i in range(20)]
>>> addFirstWord(board, 'car')
>>> findCharacter(board, 'c')
(8, 10)
Upvotes: 4