Search code examples
pythonlist-comprehension

Convert for loops to append a list into list comprehention


I'm trying to convert a 2 series 'for' loops into list comprehentions in 'places' variable.

I know list comprehentions and readability don't walk together sometimes. I'm doing this just to practicing.

Here is my code:

def win_check(board, mark):
    wins = ((1,2,3),(4,5,6),(7,8,9),(7,4,1),(8,5,2),(9,6,3),(7,5,3),(9,5,1))
    places = []
    for percorre_wins in wins:
        temp = ""
        for i in percorre_wins:
            temp+=board[i]
        places.append(temp)
    if mark*3 in places:
        return True

I've tried:

  • Change my 'places' variable: places = [temp+=board[i] for _ in wins] (I know it's wrong, but I don't know where to start.)
  • Search for another questions about this topic.

I'd apreciate your help.


Solution

  • you can just use join here

    def win_check(board, mark):
        wins = ((1,2,3),(4,5,6),(7,8,9),(7,4,1),(8,5,2),(9,6,3),(7,5,3),(9,5,1))
        places = []
        for percorre_wins in wins:
            temp = "".join(map(lambda i: board[i], percorre_wins))
            places.append(temp)
        if mark*3 in places:
            return True
    

    with 2 for

    def win_check(board, mark):
        wins = ((1,2,3),(4,5,6),(7,8,9),(7,4,1),(8,5,2),(9,6,3),(7,5,3),(9,5,1))
        places = ["".join(board[i] for i in percorre_wins) for percorre_wins in wins]
        if mark*3 in places:
            return True
    

    or

    def win_check(board, mark):
        wins = ((1,2,3),(4,5,6),(7,8,9),(7,4,1),(8,5,2),(9,6,3),(7,5,3),(9,5,1))
        places = ["".join(map(lambda i : board[i], percorre_wins)) for percorre_wins in wins]
        if mark*3 in places:
            return True
    

    PS there is a bug :P

    indexes start from 0, not from 1, correct wins

    a cleaner appronch to the problem

    def check_winner(board, mark)
      lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]]
      for line in lines:
        if mark*3 == "".join(board[i] for i in line):
          return True