先对矩阵的行进行操作,然后对矩阵的列进行操作会产生代码重复

发布于 2024-09-05 16:46:25 字数 2433 浏览 6 评论 0原文

我有以下(Python)代码来检查是否有任何行或列包含相同的值:

    # Test rows ->  

        # Check each row for a win
        for i in range(self.height):                    # For each row ...

            firstValue = None                           # Initialize first value placeholder

            for j in range(self.width):                 # For each value in the row
                if (j == 0):                                # If it's the first value ...
                    firstValue = b[i][j]                        # Remember it
                else:                                       # Otherwise ...
                    if b[i][j] != firstValue:                   # If this is not the same as the first value ...
                        firstValue = None                           # Reset first value
                        break                                       # Stop checking this row, there's no win here

            if (firstValue != None):                    # If first value has been set
                                                            # First value placeholder now holds the winning player's code
                return firstValue                           # Return it

    # Test columns ->

        # Check each column for a win
        for i in range(self.width):                 # For each column ...

            firstValue = None                           # Initialize first value placeholder

            for j in range(self.height):                # For each value in the column
                if (j == 0):                                # If it's the first value ...
                    firstValue = b[j][i]                        # Remember it
                else:                                       # Otherwise ...
                    if b[j][i] != firstValue:                   # If this is not the same as the first value ...
                        firstValue = None                           # Reset first value
                        break                                       # Stop checking this column, there's no win here

            if (firstValue != None):                    # If first value has been set
                                                            # First value placeholder now holds the winning player's code
                return firstValue                           # Return it

显然,这里有很多代码重复。 如何重构此代码?

谢谢!

I have the following (Python) code to check if there are any rows or columns that contain the same value:

    # Test rows ->  

        # Check each row for a win
        for i in range(self.height):                    # For each row ...

            firstValue = None                           # Initialize first value placeholder

            for j in range(self.width):                 # For each value in the row
                if (j == 0):                                # If it's the first value ...
                    firstValue = b[i][j]                        # Remember it
                else:                                       # Otherwise ...
                    if b[i][j] != firstValue:                   # If this is not the same as the first value ...
                        firstValue = None                           # Reset first value
                        break                                       # Stop checking this row, there's no win here

            if (firstValue != None):                    # If first value has been set
                                                            # First value placeholder now holds the winning player's code
                return firstValue                           # Return it

    # Test columns ->

        # Check each column for a win
        for i in range(self.width):                 # For each column ...

            firstValue = None                           # Initialize first value placeholder

            for j in range(self.height):                # For each value in the column
                if (j == 0):                                # If it's the first value ...
                    firstValue = b[j][i]                        # Remember it
                else:                                       # Otherwise ...
                    if b[j][i] != firstValue:                   # If this is not the same as the first value ...
                        firstValue = None                           # Reset first value
                        break                                       # Stop checking this column, there's no win here

            if (firstValue != None):                    # If first value has been set
                                                            # First value placeholder now holds the winning player's code
                return firstValue                           # Return it

Clearly, there is a lot of code duplication here. How do I refactor this code?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

゛时过境迁 2024-09-12 16:46:25

通常,当您想要重构时,请采用类似的代码片段并将它们放入函数中。因此,您可以使用一个函数来测试一个索引(行或列)相同的所有单元格,并使用另一个函数在所有列(或行)上调用该函数。尽管正如 Pär 在对您的问题的评论中指出的那样,如果您提供一些有关您尝试过的信息,那么帮助会更容易。

但是...另一个单独的(可能稍微相关的)问题是您的代码没有利用 Python 的函数功能。这很好,但正如您所知,像这样的任务,您必须检查数组(实际上是列表)的一堆不同元素,在以函数方式编写时通常更加更加简洁。例如,您的示例可以这样完成:

f = lambda x,y: x if x == y else False
# for Python <= 2.4 use this instead:
# f = lambda x,y: x == y and x or False
# test rows
[reduce(f,r) for r in array]
# test columns
reduce(lambda r,s: map(f,r,s), array)

尽管如果您试图了解代码的工作原理,那么这并没有多大帮助。

Generally, when you want to refactor, take similar snippets of code and make them into functions. So you could have a function to test all the cells for which one index (either row or column) is the same, and another function that calls that function on all the columns (or rows). Although as Pär pointed out in the comment on your question, it'd be a lot easier to help if you gave some information about what you've tried.

But... another separate (maybe slightly related) matter is that your code doesn't take advantage of Python's functional capabilities. Which is fine, but just so you know, tasks like this where you have to check a bunch of different elements of an array (list, actually) are often much more concise when written functionally. For example, your example could be done like this:

f = lambda x,y: x if x == y else False
# for Python <= 2.4 use this instead:
# f = lambda x,y: x == y and x or False
# test rows
[reduce(f,r) for r in array]
# test columns
reduce(lambda r,s: map(f,r,s), array)

although that's not so helpful if you're trying to understand how the code works.

·深蓝 2024-09-12 16:46:25

要检查一行中的所有元素是否相等,我建议构建该行的 python set,然后检查它是否只有一个元素。对于列也是如此。

例如这样

def testRowWin(b):
    for row in b:
        if len(set(row)) == 1:
            return True
    return False

def testColWin(b):
    return testRowWin(zip(*b))

To check whether all elements in a row are equal, I'd suggest building a python set of the row and then check whether it has only one element. Similarly for the columns.

E.g. like this

def testRowWin(b):
    for row in b:
        if len(set(row)) == 1:
            return True
    return False

def testColWin(b):
    return testRowWin(zip(*b))
送你一个梦 2024-09-12 16:46:25
def test_values(self, first, second, HeightWidth):
    for i in range(first):
        firstValue = None
        for j in range(second):
            (firstDimension, secondDimension) = (i, j) if HeightWidth else (j, i)
            if secondDimension == 0:
                firstValue = b[firstDimension][secondDimension]
            else:
                if b[firstDimension][secondDimension] != firstValue:
                    firstValue = None
                    break
    return firstValue

firstValue = test_values(self, self.height, self.width, true)
if firstValue:
    return firstValue

firstValue test_values(self, self.width, self.height, false)
if firstValue:
    return firstValue
def test_values(self, first, second, HeightWidth):
    for i in range(first):
        firstValue = None
        for j in range(second):
            (firstDimension, secondDimension) = (i, j) if HeightWidth else (j, i)
            if secondDimension == 0:
                firstValue = b[firstDimension][secondDimension]
            else:
                if b[firstDimension][secondDimension] != firstValue:
                    firstValue = None
                    break
    return firstValue

firstValue = test_values(self, self.height, self.width, true)
if firstValue:
    return firstValue

firstValue test_values(self, self.width, self.height, false)
if firstValue:
    return firstValue
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文