Function to check prime according to specfic instructions - python

I have to create a function according to some specific instructions. It is designed to check if a number is prime or not. I know there are different ways to do this, and I am sorry if this is a stupid question. I am new to programming.
Anyways, here are the instructions (pseudocode):
Function isPrime(n)
if n=1 then return false
else
if n<4 then return true #2 and 3 are prime
else
if n mod 2=0 then return false
else
if n<9 then return true #we have already excluded 4,6 and 8.
else
if n mod 3=0 then return false
else
r=floor( sqrt(n) ) #sqrt(n) rounded to the greatest integer r so that r*r<=n
f=5
while f<=r
if n mod f=0 then return false (and step out of the function)
if n mod(f+2)=0 then return false (and step out of the function)
f=f+6
endwhile
return true (in all other cases)
End Function
and here is my code so far: (Edited for correct indentation)
def isrime(n):
if n == 1:
return False
elif n < 4:
return True
elif n & 2 == 0:
return False
elif n<9:
return True
elif n %3 == 0:
return False
????? (Don't know what to write)
else:
return True
Thanks in advance

def isPrime(n):
if n == 1:
return False
elif n < 4:
return True
elif n % 2 == 0: # needs modulo not &
return False
elif n < 9:
return True
elif n % 3 == 0:
return False
else:
r = n**.5
f = 5
while f <= r:
if n % f== 0:
return False #(and step out of the function)
if n % (f+2)== 0:
return False# (and step out of the function)
f+=6
return True

def is_prime(n):
if n <= 3:
if n <= 1:
return False
return True
if not n%2 or not n%3:
return False
for i in range(5, int(n**0.5) + 1, 6):
if not n%i or not n%(i + 2):
return False
return True

Related

Blank List, Return False

I'm looking to write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence and returns False otherwise.
My code is correct, except when it receives something empty, like "([])". I need to account for that. Here's my code:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
if ([]):
return False
The final part is a desperate attempt to account for blank lists. More formally, it needs to pass this assertion:
assert has_evens([]) == False
You should only return True when an even is found:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
return False
Python has an any function to make this simpler:
def has_evens(s):
return any(num % 2 == 0 for num in s)
I answered my own question. I just needed to un-indent my lines
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
else:
return False

Continue while loop after return True

I am creating a function which returns True when a number(here X) is Prime.
So I am checking whether the given number is evenly divisible by integers from 2 to X-1.
But the while loop breaks when the check returns True.
Help
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while True and n < x:
if x % n == 0:
return False
else:
n += 1
return True #--The loop is breaking here--
You code should look like this:
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while n < x:
if x % n == 0:
return False
else:
n += 1
# Put the return True after the loop
return True
print('{}: {}'.format(10, is_prime(10)))
print('{}: {}'.format(11, is_prime(11)))
print('{}: {}'.format(0, is_prime(0)))
print('{}: {}'.format(1, is_prime(1)))
print('{}: {}'.format(2, is_prime(2)))
print('{}: {}'.format(113, is_prime(113)))
Output:
10: False
11: True
0: False
1: False
2: True
113: True
Well You used return statment in loop, so it exited from method. You need to change the logic of this loop. Check here:
Python Prime number checker

Why is this function with a return value returning none?

Ok, so here is my code:
def is_prime(n):
n = abs(int(n))
if n < 2:
return False
elif n == 2:
return True
elif n%2 == 0:
return False
else:
prime(n)
def prime(n):
for x in range(3, int(n**0.5)+1,2):
if n%x == 0:
return False
else:
return True
print is_prime(6577)
But whenever I run this in my shell it returns 'None', I don't understand why. Any help would be appreciated.
Your final else in is_prime returns nothing. You can even remove the else altogether, but that's just personal preference
def is_prime(n):
# You don't really need to take abs value cause you already do a check for < 2 which includes negative numbers
n = abs(int(n))
if n < 2:
return False
elif n==2:
return True
elif n%2 == 0:
return False
return prime(n)

'For' iterator in python doesn't return the right answer

I wrote this in python to calculate the number of primes under a given value. It prints "0" when I execute the code. Could anyone tell me why my code is going wrong?
def is_prime(x):
if x<2:
return False
else:
for value in range(2, x):
if x%value == 0:
return False
else:
return True
def primes_in(x):
primes = [ ]
for value in range(2, x+1):
if is_prime(value):
primes.append(1)
elif not is_prime(value):
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)
See range function.
range(start, stop[, step])
for value in range(2, x+1):
if x%value == 0:
return False
This means value goes from 2 to x included. Which means that there will necessarily be x%value == 0. So your function always return False and then primes is a list of 0.
You should use for value in range(2, x).
The issue is in your is_prime function , you are looping from 2 to x inclusive of both , so x%x is always 0 ,and hence it will always return False.
You just need to loop till the sqrt of the number.
Example code -
def is_prime(x):
if x<2:
return False
else:
for value in range(2, int(x**(1/2))+1):
if x%value == 0:
return False
else:
return True
Also, in the other function you should start
def is_prime(x):
if x<2:
return False
else:
if x == 2:
return True
for value in range(2, int(x**(0.5)) + 1):
if x%value == 0:
return False
return True
def primes_in(x):
primes = []
for value in range(2, x+1):
if is_prime(value) == True:
primes.append(1)
elif is_prime(value) == False:
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)

Why does my recursive function with if-elif statements return None?

I'm currently trying to wrap my head around learning Python and I've come to a bit of a stall on recursive functions. In Think Python, one of the exercises is to write a function that determines if number a is a power of number b using the following definition:
"A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b."
The current state of my function is:
def isPower(a,b):
return a % b == 0 and (a/b) % b == 0
print isPower(num1,num2)
As it is, this produces the result I expect. However the chapter is focused on writing recursive functions to reduce redundancy and I'm not quite sure how I can turn the final "(a/b) % b == 0" into a recursion. I've attempted:
def isPower(a,b):
if a % b != 0:
return False
elif isPower((a/b),b):
return True
But that just returns None.
What is the proper way to recurse this function?
You are forgetting a base case, when a == 1:
def isPower(a,b):
if a == 1:
return True
if a % b != 0:
return False
elif isPower((a/b),b):
return True
else
return False
However this has some other problems - if a is 0 then it will never finish and if b is 0 then you will get a divide-by-zero.
Here is a verbose solution that as far as I can tell will work for all integer combinations:
def isPower(a,b):
if a == 0 or b == 0:
return False
def realIsPower(a, b):
if a == 1:
return True
elif a%b != 0:
return False
elif realIsPower((a/b), b):
return True
else:
return False
return realIsPower(a, b)
EDIT: My code didn't work for cases when both a and b are negative. I'm now comparing their absolute values.
EDIT2: Silly me, x^0 == 1, so a == 1 should ALWAYS return true. That also means I don't have to compare a to b before the recursion. Thanks #Javier.
you need an additional case, for when both conditionals return false
def isPower(a,b):
if a % b != 0:
return False
elif isPower((a/b),b):
return True
else
return False
def isPower (a,b):
return a==1 or (a!=0 and b!=0 and b!=1 and isPower((a/b),b))
Here is my code. From what I tested, it works:
def ispower(a, b):
if b == 1 or b == 0:
return False
if b <= 0 or a <= 0:
return False
if a % b == 0:
if ((a / b) / b) == 1:
return True
else:
return ispower(a / b, b)
else:
return False
print ispower(-10, 2)
try this,
def ispower(a,b):
if b==a:
return True
elif a<b:
return False
else:
return ispower(a*1.0/b, b)
def is_power (a, b):
if a == 1:
return True
if a == 0 and b == 0:
return True
if a == 0 or b == 0:
return False
if a%b != 0:
return False
elif is_power ((a/b), b):
return True
Here's my answer, it's a little bit cleaner:
def is_power(a, b):
if a == 1:
return True
if a == 0 or b == 0:
return False
if a % b == 0 and is_power(a/b, b):
return True
else:
return False

Categories