Cleaner way of doing this?


#1

I'll admit, I've been stuck on this task for 2 hours because I felt anything more than 10 lines of code was too long
In the end, I ended up with this:

def is_prime(x):
    if x == 0:
        return False
    elif x == 1:
        return False
    elif x == 2 or x == 3:
        return True
    elif x > 0:
        for n in range(2, x - 1):
            if x % n == 0:
                result = False
                break
            else:
                result = True
        return result
    else:
        return False

Is there a cleaner, shorter, more elegant way of writing this is_prime() function? (without using built in functions which we haven't covered in previous chapters yet)


#2

Yes, there is much cleaner way of doing it. You have the makings of it, but also some flaws that will return errant results.

Consider:

    if x < 2: return False
    for ...


    return True

That takes care of everything less than 2 (which returns False) and lets 2 pass.

    for n in range(2, x):

will not let 2 into the loop since the range is too small so it falls to the last line. Any values that make it through the loop will also fall to that line.

        if x % n == 0: return False

No else line in the if or it will return True for all odd numbers.


#3

Err, sorry but I'm not getting it

I understood from your first tip that I can collapse my first 5 lines of code into:

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

The 2nd and 3rd tip you provided I was aware of and it was the reason for why I ended up with the mess of a function that I did. (or I just completely misunderstood what you meant)


#4

I randomly redid the function into this:

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

And it works, while being shorter.

But I don't understand why it works..

EDIT: Never mind, I got it, and I understand now what you meant. Thanks a lot @mtf !


#5

You don't need any of those lines.


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

We don't need to write x - 1 in the range. It already is x - 1 since x is excluded from the range.

The else on your for works because it catches everything that makes it through the loop. It's not needed though, given the above final return that catches both 2 and other primes.

Note that the else on the for didn't catch the 2, so you needed a special conditional, before. Now you don't.


#6

:thinking:

Is there a repository of "here's the best way to do it" for these lessons? It is VERY useful when you can compare your final result with that of a pro. I.E, I didn't know you don't need "else" for the last "return" after "for", but after seeing it, it makes sense that you could use it and will really end up sticking with me.


#7

It could be speculated that the athor meant 2, x when describing the range.

x = 7
range(2, x) =>  [2, 3, 4, 5, 6]

It should not be a sticking point, though, since anything past 1/2 of x cannot be divided into x. We could just as easily write,

range(2, x/2 + 1) and have enough ellimination values (factors).

We can even go so far as to set the range to only prime numbers that are no more than the square root of x if we really want to be precise. However for this deterministic, brute force approach what we have is good enough to meet our needs.


#8

Do these alternative methods of precision you've described make a program any more lightweight? Even if it's negligible?


#9

The last one especially. Just testing with the first 6 or 7 primes elliminates most of the field. In the case of smaller numbers (less than magnitude 6) the trial division approach is pretty quick. There are much faster approaches but they won't come up in these introductory courses. Look through the challenges for a couple of weeks ago for "primeNumberPrinter" and check some of the entries. I don't know if the winner has been selected but there are some good examples.


#10

That's very informative.
Thanks a lot mtf !


#11

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