simran gupta
simran gupta

Reputation: 97

using count() but unable to get the correct output

I am trying to build a tic tac toe game in python and at this stage i am finding a horizontal winner . Everything in the program is currently hard coded . According to the game list right now the first row should be the winner , but the output is wrong .

i was trying to iterate over each element in the row , but then encountered this count(), but it doesn't seem to work

game=[[1,1,1],
      [0,2,0],
      [2,2,0 ]]

def win(current_game):
    for row in current_game:
        print(row)
        if (row.count(row[0]==len(row))==True):
            print("winner", row[0])

win(game)

the output i got is :-

[1, 1, 1]
[0, 2, 0]
[2, 2, 0]
winner 2

but the correct output should be :-

[1,1,1]
winner 1
[0,2,0]
[2,2,0]

Upvotes: 0

Views: 61

Answers (1)

Fabian
Fabian

Reputation: 100

To my understanding, row.count(obj) returns how many times obj occurs in your row object. Reference

So, row[0]==len(row) being a comparison and returning either true or false doesn't make sense here. With row.count(row[0]==len(row)) you are checking if true or false occurs in row and not a number.

What you want is to check if your first item in your list occurs three times (or whichever length the list is).

def win(current_game):
    for row in current_game:
        print(row)
        if (len(row) == row.count(row[0])):
            print("winner", row[0])

Upvotes: 4

Related Questions