Operating on rows and then on columns of a matrix produces code duplication

Posted by Chetan on Stack Overflow See other posts from Stack Overflow or by Chetan
Published on 2010-06-16T08:06:00Z Indexed on 2010/06/16 8:22 UTC
Read the original article Hit count: 254

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!

© Stack Overflow or respective owner

Related posts about python

Related posts about refactoring