The problem is that when you break, you don't end both loops -- only the second one.
Consequently, when your code finds the first P
, it increments inRow
until it equals 5, then breaks. Then your code moves on to the second row, to the second P
, and increments inRow
until it equals 9
-- 5 + 4 = 9
.
Although you can restructure your code to avoid this issue altogether, you can also wrap the code in a function and simply return instead of breaking:
board = [['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']]
def find(board):
inRow=0
for y in range(10):
x = 0
for pos in board[y]:
if pos == "P":
for i in range(5):
if board[y+i][x] == "P":
inRow += 1
return inRow
x += 1
return inRow
print(find(board))