Operativo en filas y, a continuación, en las columnas de una matriz produce la duplicación de código
-
27-09-2019 - |
Pregunta
Tengo el siguiente (en Python) código para comprobar si hay alguna de las filas o columnas que contienen el mismo valor:
# 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
Claramente, hay un montón de duplicación de código aquí. ¿Cómo puedo refactorizar este código?
Gracias!
Solución
Generalmente, cuando se quiere refactorizar, tome similar fragmentos de código y hacer de ellos las funciones.Así que usted podría tener una función a prueba de todas las células para que un índice (fila o columna) es el mismo, y otra función que se llama a esa función en todas las columnas (o filas).Aunque como Pär señalado en el comentario a tu pregunta, que iba a ser mucho más fácil ayudar si se dio alguna información sobre lo que has probado.
Pero...otro (tal vez un poco relacionado con el asunto es que el código no tomar ventaja de Python capacidades funcionales.Lo cual está bien, pero solo para que lo sepas, las tareas de este tipo donde tienes que revisar un montón de diferentes elementos de un array (lista, en realidad) son a menudo mucho más conciso cuando escrito funcionalmente.Por ejemplo, su ejemplo se podría hacer así:
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)
a pesar de que no es tan útil si usted está tratando de entender cómo funciona el código.
Otros consejos
Para comprobar si todos los elementos de una fila son iguales, me gustaría sugerir la construcción de un python set
de la fila y, a continuación, compruebe si tiene un solo elemento.Lo mismo para las columnas.
E. g.como este
def testRowWin(b):
for row in b:
if len(set(row)) == 1:
return True
return False
def testColWin(b):
return testRowWin(zip(*b))
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