我有以下(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
显然,这里有很多代码重复。如何重构此代码?
谢谢!