hey bros I don’t like this I am pretty sure there is an additional step being made which is not necessary and shouldn’t be there.
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x-1): #I MEAN THIS LINE RIGHT HERE
if x % n == 0:
return False
return True
print is_prime(13)
print is_prime(10)
Why is there the (-1) I don’t think it should be there. Or I am just tired and it still counts it from 0… like. Range(2)… 0, 1 and then stop at x-1 for instance 10 which would mean 9, numbers 2 to 9 that is… 1, 2, 3, 4, 5, 6, 7, 8, 9… oh god damnit I see now, somebody please confirm I understand. Wait no need to I get it.
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x-1):
if x % n == 0:
return False
return True
print is_prime(13)
print is_prime(10)
print is_prime(15)
def is_prime(x):
if x == 2:
return True
if x < 2:
return False
else:
j = 0
for n in range (2, x):
if x % n == 0:
return False
return True
print is_prime(2)
print is_prime(3)
print is_prime(4)
print is_prime(5)
print is_prime(6)
print is_prime(7)
print is_prime(8)
print is_prime(9)
Hi, I was wondering if someone could help me solve my code’s problem with the 9 (the print statements are only to verify answers as you can see). It doesn’t count 9 as a prime and I was wondering why. lately, I have been troubled by multiples and 9 appears to persist somehow.
btw if a branch returns then the code that comes after the if-statement is already exclusive and doesn’t need to be inside else and the additional indentation that comes with it
if something
exit like so
otherwise do something else
another thought is that the iteration you’re doing is “any” - if any of these numbers divide this number
several loop concepts have function equivalents, and any is one of them
And yeah I’m already using some silly fancy things.
return not any(x % d == 0 for d in range(2, x))
could also…
divisors = range(2, x)
dividesX = lambda d: x % d == 0
return not any(map(dividesX, divisors))
… I’m probably just making things complicated.
but at the same time, simpler, because I’m no longer writing the loop.
Figure out all the potential divisors (range)
Define a test for a single divisor (given a number d, does d divide x?)
Apply the test to each divisor (map)
Check if any passed (any)
True. I believe this was one of the many mistakes I see people doing in this exercise (And I committed it myself as well), as you tend to think that you need to specify the program to go over other characteristics, despite it not being needed. (In reality, it wouldn’t make a difference, but rather add a line. Though, the fewer lines the better so…)
Not exactly. I mean, your second theory would be probably equivalent to the for loop idea in terms of lines, maybe faster as it is done through functions. But the first one seems pretty simple an good-looking.