Is_prime - My code seems long!


#1

Hi

I have completed the exercise with the code below which I came up with. It is the result of some experimentation but I understand it. However looking on the forum some of the code people come up with look so short!

Is there anything I am doing which could be done more efficiently?

Thanks

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    elif x%2==0:
        return False
    else:
        prime = True
        for n in range(2,x-1):
            if x % n != 0 and prime ==True:
                prime = True
            else:
                prime = False
            
        return prime

#2

this code indeed seems a bit lengthy. without making it super complicated here is how you could reduce, first lets catch numbers which are lower then 2, since they are all not prime numbers:

def is_prime(x):
   if x < 2:
      return False

right, that is simple. now we could already start looping over the values:

def is_prime(x):
   if x < 2:
      return False
   for n in range(2,x):

i don't use -1 here, given range() will not include the stop values. so x is not included, only values lesser then x, so need to do minus 1

now we could simply check if the number is not a prime by checking if the remainder equals zero:

def is_prime(x):
   if x < 2:
      return False
   for n in range(2,x):
      if x % n == 0:
          return False

A function ends the moment a return keyword is reached, so if now one the values between 2 and x has a remainder of zero, False is returned, the function ends. Which is right, given once a remainder is zero, the number is not a prime number

so the only way for a number to be a prime number is after the loop finished running, so all we than have to do is simply return True:

def is_prime(x):
   if x < 2:
      return False
   for n in range(2,x):
      if x % n == 0:
          return False
   return True

#3

Hi

Thanks for the quick reply. You explained that brilliantly - hopefully going forward I can think more efficiently.


#5

The question by microslaver36410 highlighted that I also definitely need to become more code efficient.

Unfortunately I have a problem with the solution as when I use the solution provided, the code says that it fails on is_prime(2) due to it returning False when it should return True. If I say elif x == 2: return True, then it says that it fails on is_prime(3) due to it returning False. Due to these fail statements this is why I created my code:.

def is_prime(x):

     if x > 3:
        count = 0
        for n in range(2, x-1):
            if x % n == 0:
                count += 1
            else:
                count = count
        if count > 0:
            return False
        else:
            return True

    elif x == 3 or x == 2:
        return True
    else:
        return False

Can you please explain to me why:

def is_prime(x):
   if x < 2:
      return False
   for n in range(2,x):
      if x % n == 0:
          return False
   return True

doesn't work?


#6

my solution:

def is_prime(x):
   if x < 2:
      return False
   for n in range(2,x):
      if x % n == 0:
          return False
   return True

does work, right?


#7

Super sorry, when I tried it earlier it didn't work, but it does indeed work now.
I will remove my reply as it will confuse others looking at the site.
What frustrates me is that when I read your solution, it made perfect sense that it should work, that is why I tested it. And when I got the fail response, I couldn't understand why.
But I have just run the code again, and now there seems to be no problem at all.


#8

sometimes, your browser might send cached data, that might be confusing.

And here is the big problem: reading my solution make perfect sense, now try to build it.

There is a difference between coding and programming, and codecademy mostly focus on coding.


#9

Yeah, I've just been back to the python window to see if the code I input earlier worked now due to maybe the browser causing an issue, and it failed again with the same comment.
I then wrote the code out word for word, and it failed again with the same comment
But the code I just copied from your response now and pasted, that worked.
I think it has something to do with the indentation as this latest one is slightly off the set indentation.

What's even more frustrating is that I had written code almost similar to your answer, and it gave me the same reply about failing on is_prime(2) and is_prime(3). Hence me going on the long-winded route to ensure that it passed those two.

I had to look up the difference between the two as even though I am married to a software developer, I didn't think that programming and coding were different. But I see that they are and I agree that right now I'm only being taught coding. Which is fine by me as I have been trying to learn Java for a while, but never quite grasped the concept of lists and dictionaries (arrays)... once I have the coding knowledge, I want to learn how to use it to do programming which will involve practice using code to build a solution as well as practice editing code to make it more efficient.


#10

okay, but it works now? and you understand why it works?

the tricky bit with my code is is_prime(2), because the if statement is false, so it continues to the for loop: for n in range(2,2) no steps can be taken, so it moves on, and finds return True.

oh they are, but you can start with coding, and then move on to programming.

Sounds like a good plan :slight_smile:


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.