I was expecting the returned counts to be 5 as in 5 'a's in the nested loops, but it returns counts as 1.
CodePudding user response:
You could fix the second loop to:
for j in range(len(fleet_grid[i])): # then loop each of item in col.
CodePudding user response:
Try this and it should help you understand what's missing (wrong): (it's very easy to just add a few print here-n-there to see what's happening is what's supposed to)
Also it's helpful to learn how to debug such a small program next time - use visual platform like https://pythontutor.com/
grid = [['a', 'a', 'a'], ['b', 'b', 'b'], ['1', 'a', 'a']]
counts = 0
rows = len(grid)
cols = len(grid[0])
for i in range(rows):
for j in range(cols): # if alll columns are the same size
#for j in range(len(grid[i])): # if not all col. have the same size
if grid[i][j] == 'a': #
print(i,j)
counts = 1
print(counts) # 5
Alternatively, you can do this way: (but not recommend for learning:)
flatted = sum(grid, [])
print(flatted)
counts = sum(1 for x in flatted if x == 'a') # sum(*generator exp.*)
print(counts) # 5
CodePudding user response:
Try changing
for j in range(i)
to
for j in range(len(fleet_grid[i]))
otherwise you're not counting every character.