coderWorld
coderWorld

Reputation: 642

How to add a limit in the generator expression Python

I have a function in Python which returns true if all rows or columns in a grid matrix are the same value. However, I want my function to stop iterating and return True as soon as 4 of them match, irrespective of the size of the grid. How can I modify the generator expression I have below to achieve the same?

def check_won(grids, user, n):
    return any(all(cell == user for cell in grid) for grid in grids)

To illustrate further, I am sharing my example output:

Input the grid size: 5
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[0, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 2 from 1 to 5: 2
Current board:
[0, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Input a slot player 1 from 1 to 5: 1
Current board:
[1, 0, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
[1, 2, 0, 0, 0]
Player 1 has won

As can be seen this doesn't exit with 4 matches (match 4), but needs the whole column (5 elements shown here) or row to match.

Upvotes: 1

Views: 224

Answers (1)

Gareth Ma
Gareth Ma

Reputation: 707

Using any instead of all actually works in this case. All is just printing 1 for all the rows/ columns.

def check_won(grids, user, n):
    cnt = 0
    for grid in grids:
        if any(cell == user for cell in grid):
            cnt += 1
            if cnt == 4:
                return True
    return False

Upvotes: 1

Related Questions