Python: does it make sense to refactor this check into it's own method?
- by Jeff Fry
I'm still learning python. I just wrote this method to determine if a player has won a game of tic-tac-toe yet, given a board state like:'[['o','x','x'],['x','o','-'],['x','o','o']]'
def hasWon(board):
players = ['x', 'o']
for player in players:
for row in board:
if row.count(player) == 3:
return player
top, mid, low = board
for i in range(3):
if [ top[i],mid[i],low[i] ].count(player) == 3:
return player
if [top[0],mid[1],low[2]].count(player) == 3:
return player
if [top[2],mid[1],low[0]].count(player) == 3:
return player
return None
It occurred to me that I check lists of 3 chars several times and could refactor the checking to its own method like so:
def check(list, player):
if list.count(player) == 3:
return player
...but then realized that all that really does is change lines like:
if [ top[i],mid[i],low[i] ].count(player) == 3:
return player
to:
if check( [top[i],mid[i],low[i]], player ):
return player
...which frankly doesn't seem like much of an improvement. Do you see a better way to refactor this? Or in general a more Pythonic option? I'd love to hear it!