I don't know why such an easy syntax result in mistake. Can anyone help me to see if I missed out any?
This part only tries to check if a particular (num) is prime or not.
Not sure why my check_primes(10) results into 'PRIME'. Cuz I'm looping through y from 3,4,5,6,...,9-> then 10%5==0, I suppose it returns true and 'Non PRIME' is the result.
Do I do any wrong in my loop?
def check_primes(num):
for y in range(3,num):
if num%y==0:
return 'Non PRIME'
else:
return 'PRIME'
A way to return 'PRIME' or 'Non PRIME' as in your example:
def check_primes(num):
is_prime = True
for y in range(3,num):
if num % y==0:
return 'Non PRIME'
else:
continue
return 'PRIME'
You will return 'Non PRIME' the moment you can verify the number is not prime. Alternatively if you succeed in all your checks, you will return 'PRIME' as desired.
(Note that this is not a very efficient way to get primes)
(Note also that the comment below is correct, this method works exactly the same way with or without the else clause)
The definition of "prime" states that a number is prime if and only if it is only divisible by 1 and itself. This means that a number is not prime if you find one number from 2 to n-1 which divides n. To check that a number is prime, you must check every number from 2 to n-1. Your code stops immediately after testing divisibility by 3 in both cases.
You should use print instead of return. You are breaking your loop when you return it.
Related
so pretty straight forward, I had to write a code to check if a number if Prime or not. Code tested on Jupyter Notebook and works PERFECTLY. But whenever I put it in CodeWars, it passes the initial tests but later on when I submit the attempt, it times out, saying that the code may be "inefficient". Does anyone have an insight as to why this might be happening? Here is the code:
def is_prime(num):
mylist = []
if num != 1 and num > 0:
for number in range(1,num+1):
if num % number == 0:
mylist.append(number)
else:
pass
if len(mylist)>2:
return False
else:
return True
else:
return False
For large numbers, your time to compute will take too long.
I suggest looking more into the properties of prime numbers and reevaluating your code.
Ex: Properties of Prime Numbers!
can you try this and see how it works in CodeWars.
for num in range(1,7):
if all(num%i!=0 for i in range(2,num)):
print('Prime' , num)
I am trying to make a function that tells you if a number is prime or not using the any() method. This is what I have:
def prime(n):
if any(n % i == 0 for i in range(1, n + 1)) != True:
print("Prime")
else:
print("Not Prime")
prime(5)
However it is giving me:
Not Prime
every single time, even when I give a prime number.
Can someone please help me out?
Everything is divisible by 1, so that check will consider everything as non-prime. You need to set the lower bound to check to 2 instead.
As pointed out in the comments by #ForceBru, the upper bound is incorrect as well. You don't want to check if n is divisible by itself, since it always will be.
Change your range in the comprehension to just:
range(2, n))
I am really sorry for the vague title but I don't really know the specifics of what's happening with my code. I am currently learning Python and finding it interesting so far. I am practicing the concept of generator functions and wrote a little program that finds palindromes using a generator function.
Here is the code (Python 3.6, written in Spyder):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>1131: break
print('{} is a palindrome'.format(n))
When ran I get this output:
1111 is a palindrome
1121 is a palindrome
1131 is a palindrome
Needless to say the output is completely wrong. I added a few prints in my code and tried to find out the issue and it looks like the program is exiting the for loop inside ispalindrome() function early. It is exiting the for-loop as soon as it encounters two digits and two ends which match, when this should not be the case. Is it because of the break keyword somehow?
I will greatly appreciate if someone can point out what am I doing wrong with this code and how should I approach this correct the issue. Thanks in advance!
I think your problem is that you've got the idea backwards.
With the current format of your code you should be assuming it IS a palindrome and breaking when you discover it is not.
Instead you are assuming it is not, then setting it to "it is" the first time you see equality. But then the next time you see inequality you merely break without setting it to false again.
If I were to code this I wouldn't bother with a flag, I would merely return "false" the moment an inequality was found.
Your logic isn't right.
By default, you think the number is not a palindrome (flag=False), and if you see a mirrored int, you set the flag to true (if l[n]==l[i-n]: flag=True).
You should do the contrary. You should set the flag to True by default, and if an item is not mirrored, return a flag to False.
As pointed out by the fellow users, my code was clearly logically in the wrong. I was never setting back flag variable to False whenever I was exiting from the for loop. So I took in account the suggestions made and changed my code.
Here is the code following my previous solution with a flag variable:
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
flag=False
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]==l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
flag=True
else:
flag=False
break
#if n>(len(l)-1)-n
else:
break
#returns the flag
return flag
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
And here is the one suggested by both Blusky and Fredman (more efficient than mine to say the least):
def ispalindrome(n):
#creates a list for storing the element of the number one by one
l=[]
#storing the digits
while n!=0:
l.append(n%10)
n=int(n/10)
#setting useful variables
i=len(l)-1
#traversing the list and checking whether palindrome
for n in range(0,len(l)):
#this block is executed only if n is less than (len(l)-1)-n
if n<i-n:
#comparing elements
if l[n]!=l[i-n]:
#flag is set to true everytime l[n] equals l[(len(l)-1)-n]
return False
#if n>(len(l)-1)-n
else:
break
#returns the flag
return True
#basic generator function that yields whenever ispalindrome() returns true
def palindromes(n=1111):
while True:
if ispalindrome(n): yield n
n+=1
#traversing through palindromes generator function
for n in palindromes():
if n>2552: break
print('{} is a palindrome'.format(n))
P.S: I am neither a professional s/w dev nor have I access to high quality courses or a mentor, that's why question boards like stackoverflow is useful for me. I know this is a dumb question and if I thoroughly checked my code again and again I might have realized the mistake, but I don't think it requires a downvote, does it?
I need to write a code in Sage for a homework problem that checks whether a random number generated between 10^7 and 10^8 is prime by dividing it by all the known primes less than or equal to 10^4. I have never programmed in Sage prior to this as a warning. This is what I have so far.
# This creates a function to create a random number between two numbers
def random_between(j,k):
a=int(random()*(k-j+1))+j
return a
# Testing that the function works, which it does, though I don't know how
# to assign a variable to it like x=random_between(10^7,10^8)
random_between(10^7,10^8)
# The list of primes less than 10^4 is given by
list_of_primes = prime_range(1,10^4)
# Want to write a function to check if prime
def check_if_prime(n):
for n in list_of_primes:
if n % random_between(10^7,10^8)==0:
print 'number is prime'
else
print 'number is not prime'
What I'm wanting to do is to use determine whether the numbers in list_of_primes divide the random number generated from random_between using the % command and then print that number x is a prime or that it's not.
I do know that the command Primes() will check whether a number is prime or not, but we are specifically supposed to do this "naive" check primality.
If someone could help me out with this I would really appreciate it.
You're check_if_prime function could use some work. I've re-written below.
def check_if_prime(): # there's no parameter for this method since we're checking against the global var list_of_primes
for n in list_of_primes:
if random_between(10^7,10^8) % n == 0: # if a random number / a prime number has no remainder, the random number is not prime
print 'number is not prime'
return # we're done, we know it's not prime
print 'number is prime' # we made it through all of our tests, the number might be prime
i wanna write a function that if the number is prime the function gives it as a result,but for non prime numbers i get a None,here is my code:
def isprime(n):
a=0
if n==1:
a=1
if n==2:
a=1
for i in range(2,n):
if n%i==0:
a=0
break
else:
a=1
break
if a==1:
return n
if a==0:
return
print(isprime(68))
the result for 68 is None
If you don't want to print None when you get that returned from your function, you need to change the printing code, rather than the function's code. Use something like:
p = isprime(x)
if p is not None:
print(p)
But your isprime function isn't actually working properly anyway. It will always return None for any value other than 2 or 3.
This is because the for loop will run only a single iteration, because you always hit a break statement in the if or else block it contains. You don't want to break if the number you tested is not a divisor. In fact, you don't need to do anything in that case.
Just use:
for i in range(2,n):
if n%i==0:
a=0
break
with no else block.
Note that you could simplify it a bit by using a return in the if block rather than setting a flag variable (which should really be given a more meaningful name than a if you do intend to keep it).
Here's a streamlined version of the same algorithm. I've added a few improvements, such as stopping the range after int(sqrt(n)), and iterating only on odd values (since 2 is handled by a special case at the beginning). I'm also explicitly naming None as the return value, to make it clear that it is intentional to return that value when n is a composite (a bare return makes it seem like the None is supposed to be ignored):
def isprime(n):
if n==1:
return None
if n==2:
return 2
for i in range(3,int(math.sqrt(n))+1,2):
if n%i==0:
return None
return n
In the case of not a prime number (a=0) you return nothing:
if a==0:
return
and if you print the value of a function which returns nothing, it prints None.
To solve this, return a number, or in this case a boolean would be more logical. So instead of setting a=0 or a=1 you can use a=False and a=True. Then you can do return a.
It is usually good practice in methods that require you to print something out to have a "base-case" because you should never get a none-type because you will always be returning something back to the print/calling function.
a=0
if n==1:
a=1
if n==2:
a=1
for i in range(2,n):
if n%i==0:
a=0
break
else:
a=1
break
if a==1:
return n
# By having a base case return statement we will
# never print out a none type, even upon error.
return (n + 'is not prime')