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


I have the following Python code to check if there are any lines or columns that have the same values: / P> # Exam Rows - & gt; Check for each line to win for i for category # (self.height): # For each line ... firstValue = None # Start the first value placeholder for J in the range (self.width): # For each value in the row (Jammu == 0): # If this is the first value ... first value = b [i] [j] # and remember it: # Otherwise ... if b [ii] [j ]! = First value: #If this is not the same as the first value ... First value = none # Reset the first value # Stop blocking this line, if there is no win here (first value! = None): # If the first value is set # The first value placeholder now considers the winning player returns the code first # Return it #Test column - & gt; Check each column for a win for i in #category (i.width): # For each column ... firstValue = None # Start the first value placeholder for jm (self.height) in the range: # For each value in column (J == 0): # If this is the first value ... firstval = b [ja] [i] # Remember it: # Otherwise ... if B [J] [I]! = First value: # if it is not the same as the first value ... first value = none # reset the value break first # stop blocking this column, if there is no win here (first value! = None) : # If the first value has been set #fir St. Valle Placeholder now puts the winning player code code first. Value # Return

Clearly, there are many code repeats here How can I refter this code?

Thank you!

Generally, when you want to refactor, take the same snippet of code and create them in the function So you can do a function to test all the cells, for which an index (either line or column) is the same, and another function that calls that function to all columns (or rows). However, in a comment on your question, Vare told that if you have given some information about what you have done, then it will prove helpful.

But ... Another different (perhaps a bit related) thing is that your code does not take advantage of Python's functional capabilities. That's fine, but well, you know that in this way, where you have to check the list of different elements (list, in fact) of an array, when often written in functionally written More are more concise, for example, your example can be done like this:

  f = lambda x, y: x if x == y and false # python For & lt; = 2.4 Use it instead: # f = lambda X, Y: X = YY and X or False # for the array in R [R (Reduce F, R)) # Test column less (Lambda R, S : Map (F, R, S), array)  

However this is not very useful if you are trying to understand how the code works.


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -