Reputation: 11
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','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']
]
Upvotes: 0
Views: 2229
Reputation: 882491
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?-)
Upvotes: 4
Reputation: 304413
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)])
Upvotes: 2
Reputation: 414745
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
Upvotes: 1
Reputation: 16625
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
Upvotes: 4