我正在尝试创建一个检查程序,以查看该单词是水平还是垂直的矩阵。我有检查行的代码,但检查列是否与行代码类似?
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','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']
]
答案 0 :(得分:4)
这样不简单:
def checkCol(table, r, pos, word):
for i in range(0, len(word)):
if table[r+i][pos] != word[i]:
return False
return True
答案 1 :(得分:4)
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]))
OP表示“他们尚未学习导入”,所以他们宁愿重新发明轮子而不是标准库中的重用功能。总的来说,这将是一个非常荒谬的立场,但在这种情况下,它甚至不是太糟糕:
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]))
我希望至少内置诸如all
和zip
这样的内容是可以接受的 - 或者OP会将二进制机器语言编码为裸机以避免学习某些蟒 - ?)
答案 2 :(得分:2)
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)])
答案 3 :(得分:1)
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