I am trying to create a checking program to see if the word is in a matrix horizontally or vertically. I have the code for checking the row, but would checking the column be similar to the row code?
def checkRow(table, r, pos, word):
for i in range(0, len(word)):
if table[r][pos+i] != word[i]:
return False
return True
a sample table would be like this:
[
['a','p','p','l','e','b'],
['u','y','c'开发者_C百科,'v','a','s'],
['n','u','t','o','n','s'],
['t','n','c','v','d','b'],
['o','r','i','x','o','f'],
['e','a','t','i','n','g']
]
Isn't it simple like this:
def checkCol(table, r, pos, word):
for i in range(0, len(word)):
if table[r+i][pos] != word[i]:
return False
return True
import itertools
def checkRow(table, r, pos, word):
return all(w==x for w, x in itertools.izip(word, table[r][pos:]))
def checkCol(table, r, pos, word):
return all(w==x for w, x in itertools.izip(word, table[r:][pos]))
The OP indicates "they haven't learned about import yet" so they'd rather reinvent the wheel than reuse functionality in the standard library. In general, that would be a pretty absurd stance, but in this case it ain't even too bad:
def checkRow(table, r, pos, word):
return all(w==x for w, x in zip(word, table[r][pos:]))
def checkCol(table, r, pos, word):
return all(w==x for w, x in zip(word, table[r:][pos]))
I hope at least builtins such as all
and zip
are acceptable -- or would the OP rather code binary machine language down to the bare metal to avoid learning some Python?-)
def checkRow(table, r, pos, word):
return word=="".join(table[r][pos:pos+len(word)])
def checkColumn(table, r, pos, word):
return word=="".join(row[pos] for row in table[r:r+len(word)])
def intable(table, word):
if any(word in ''.join(row) for row in table): # check rows
return True
return any(word in ''.join(col) for col in zip(*table)) # check columns
精彩评论