Use the Design Recipe to write a function count_evens_NxN, that consumes a nested list representing a matrix of size NxN. The function should return the number of even numbers in the matrix. For this function, 0 is considered an even number. Include a Docstring!
Note: You may assume the list argument passed to the function is a nested list of integers.
Write 3 assert_equal statements to test your function.
Code Screenshot :
Executable Code:
import unittest
#Required function
def count_evens_NxN(nested_list):
#Variable to store result
result=0
#Iterating the matrix
for i in nested_list:
for j in i:
#Checking if the number is even
if(j%2 ==
0):
#Keep track of even numbers
result += 1
#Return the result
return result
#Class for assert testing
class Testing(unittest.TestCase):
#3 Tests
def test1(self):
self.assertEqual(count_evens_NxN([[1,2],[8,16],[3,4]]), 4)
def test2(self):
self.assertEqual(count_evens_NxN([[7], [18]]), 1)
def test3(self):
self.assertEqual(count_evens_NxN([[]]), 0)
if __name__ == '__main__':
unittest.main()
Sample Output :
Get Answers For Free
Most questions answered within 1 hours.