Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 😛

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading