-1

Using the matrix below as an input I want to count even numbers and odd numbers in matrix Matrix:

1 4 7 5 8
8 5 9 11 9

To do this I write the matrix value in python, and is two loops is the correct way to solve this

numbers= [[1,4,7,5,8],[8,5,9,11,9]]
Manha
  • 1
  • 2
  • 2
    Please post the expected result. – Red Dec 11 '20 at 13:54
  • 1
    Please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822). Do you know how to iterate over a list? Do you know how to check if a number is even or odd? Do you know how to keep a running total? If so, just combine that knowledge. If not -- explain which of those you find hard. As it is, the question is too broad since you have given no indication as to where the trouble lies. – John Coleman Dec 11 '20 at 13:56
  • 2
    I'd suggest starting with [How to make a flat list out of list of lists?](https://stackoverflow.com/q/952914/364696); now you've got a 1D `list`, and it's a lot easier to work with. If you're not sure how to do it at that point, you need to talk to your teacher/tutor or work through a tutorial. – ShadowRanger Dec 11 '20 at 13:57

3 Answers3

0

here's a simple to understand implementation for your problem. This code uses the % operator in python. Link to an explanation : https://www.freecodecamp.org/news/the-python-modulo-operator-what-does-the-symbol-mean-in-python-solved/

numbers= [[1,4,7,5],[8,5,1,11]]

even = 0 #count for even numbers

odd = 0 #count for odd numbers

for i in range(len(numbers)): 

  for j in range(len(numbers[i])): #loop visit value in matrix 

    if(numbers[i][j]%2==0): #if the number is even add +1 to the counter

      even +=1

    else:

      odd+=1

#print output

print(even)

print(odd)
Manha
  • 1
  • 2
wakkko
  • 61
  • 5
0

Once you understand how the answer above work, you can try using numpy to make your code cleaner,faster and easier to read.

import numpy as np
numbers= np.array([[2,5,6],[9,3,8],[1,4,7]])

odd = numbers[numbers%2 == 1].size
even = numbers[numbers%2 == 0].size

print(odd, even)
Lorenzo Gutiérrez
  • 105
  • 1
  • 1
  • 10
0

As ShadowRanger suggested, you should try to flat the nested list first, to make checking easier:

Sample code snippets:

>>> flattened = sum(numbers, [])
>>> flattened
[2, 5, 6, 9, 3, 8, 1, 4, 7]
>>> evens = [x for x in flattened if x%2 == 0]
>>> evens
[2, 6, 8, 4]
>>> odds = [x for x in flattened if x%2]
>>> odds
[5, 9, 3, 1, 7]
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23