在Python中检查行和列中的单词
我正在尝试创建一个程序,用来检查一个单词是否在一个矩阵中水平或垂直出现。我已经有了检查行的代码,但检查列的代码会不会和检查行的代码类似呢?
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']
]
4 个回答
2
在编程中,有时候我们需要在代码里插入一些特定的内容,比如变量的值或者其他信息。这就像在写作文时需要用到一些例子来让内容更丰富。
有些时候,我们会用到一种叫做“占位符”的东西。占位符就像是一个空白的框,等着我们在里面填上具体的内容。比如说,如果你在写一封信,可能会写“亲爱的[NAME]”,然后在[NAME]的地方填上收信人的名字。
在代码中,类似的占位符可以帮助我们更灵活地处理数据。比如说,我们可以用
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)])
来表示某一段代码,等到需要的时候再把具体的代码放进去。
总之,占位符让我们的代码更简洁,也更容易管理,就像在写作时用到的例子和空白框一样。
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]))
提问者表示“他们还没有学习过导入(import)的内容”,所以他们宁愿自己重新发明轮子,也不想使用标准库中的功能。一般来说,这种态度是相当荒谬的,但在这种情况下其实也没那么糟:
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
这样的内置函数是可以接受的——或者提问者宁愿直接编写二进制机器语言,完全不使用某些 Python 的功能吗?-)
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