Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

what I'm doing wrong?? i want to find prime numbers in matrix and add in a new list (PYTHON)

0 votes
asked Apr 2 by Lilit (150 points)

lst1=[ ]

lst2=[ ] 

import numpy as np 

n=3 

m=4 

mat=np.random.randint(10, size=(n,m)) 

print(mat) for i in range(n):

 for j in range(m): 

for a in range(2, mat[i][j]):

 if mat[i][j]%a!=0: 

lst2.append(mat[i][j]) 

break

 else:

lst1.append(mat[i][j])

print(lst1)

1 Answer

0 votes
answered Apr 9 by Peter Minarik (55,250 points)

First of all, you should create meaningful variable names. For instance, what are lst1 and lst2? Wouldn't it make more sense to call them primes and compounds?

Your test for primes is logically incorrect. What you do is this:

  1. Test if a number can be divided without any remainder by a
  2. If there is a remainder, you put it into list1 (primes?, compound numbers?) and stop the loop
  3. If there is no reminder, you put it into list2, but you keep doing your innermost loop so potentially you would put the same number in the other list as well or even the same list again.

A correct (but not the most efficient) way to test for prime would be like this (your loop conditions are correct: for a in range(2, mat[i][j]))

  1. If the number in test can be divided by any of the values of a, then it is a compound number. Put it in the compounds list and terminate the innermost loop.
  2. If you finish the innermost loop without putting your a into the compounds list, then it had no whole dividers, hence it is a prime and should go into the primes list.

I hope this helps.

Good luck with the implementation!

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...