-3
def count(matrix: list, number: int):

    count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)

I am trying to make function that counts all zeros or any other number from matrix list but for now its 0.

  • Because your input list contains only lists none of each equals 0. You need to [flatten it](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists) first – Yevhen Kuzmovych Sep 03 '21 at 13:59
  • So what does your code look like right now? – Shinra tensei Sep 03 '21 at 14:00
  • Also, does this answer your question? [python .count for multidimensional arrays (list of lists)](https://stackoverflow.com/questions/17718271/python-count-for-multidimensional-arrays-list-of-lists) – Yevhen Kuzmovych Sep 03 '21 at 14:01

2 Answers2

1

try this:

def count(matrix: list, number: int):
    return sum(l.count(number) for l in matrix)

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)
# 9

count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 6)
# 2
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
0
import itertools
def count(matrix: list, number: int):
    return list(itertools.chain.from_iterable(matrix)).count(number)
    
count([[1, 4, 0, 0, 6, 3], [0, 3, 4, 0, 0, 0], [0, 0, 5, 6, 0]], 0)

9

Eleko
  • 1
  • 1