This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Getting wrong answers for prime numbers
(4 answers)
Closed last year.
def primetest(n):
if n<=1:
return false
"""Test if N is prime"""
for i in range(2,int(n/2)+1):
if(n%i)==0:
return false
return true
Hello so above I have my code that tells you if n is prime or not by returning true or false. Now I need to write a method called primelist() which inputs a positive integer n and outputs an ordered list of primes 2 through p. Below I have added my code but when I go to test it, for example, I test primelist(7)==is_prime(7) I get false but I should be getting true.
def primelist(n):
for i in range(2,n+1):
if primetest(i):
print(I,end=" ")
In order to test if the number is prime you need to check all the integers from 2 to the square root of n. Only if for none of them, n is divisible can you be sure it's a prime number.
Also as pointed out in the comments there are some syntactic/indentation issues e.g. True and False need to be capitalized.
def primetest(n):
# Test if N is prime
if n <= 1:
return False
for i in range(2,int(n**(1/2))+1):
if(n%i)==0:
return False
return True
Edit: to work for integers less than 2 you have to treat these separately.
For the 2nd part of your question primelist(7)==is_prime(7) will always be False, because you're comparing a boolean with None type (since your 2nd function doesn't actually return anything).
Also the following might give a nicer output:
def primelist(n):
primes = []
for i in range(2,n+1):
if primetest(i):
primes.append(i)
print(*primes, sep = " ")
Related
This question already has answers here:
Is the shortcircuit behaviour of Python's any/all explicit? [duplicate]
(4 answers)
Closed 9 months ago.
Will python's all function exit as soon as it finds a False in the iterable? Or will it continue checking the rest?
For example, if i is not divisible by 20, will the below code continue checking if it is divisible by 19 and 18 and so on?
def min_divisible(target_n):
'''
Returns the smallest number that is divisible by all integers between 1 and n
'''
i = target_n
while not all((i%j == 0) for j in range(target_n,2,-1)):
i+=target_n
return f'{i:,}'
print(min_divisible(20))
all will stop the iteration as soon as it encounters a "falsey" object. You can see this with a simple example:
def produce_numbers():
for k in range(10):
yield k
print(k)
all(k < 3 for k in produce_numbers())
This prints
0
1
2
This is spelled out in Python's documentation. It states that the following is a functionally equivalent definition of all:
def all(iterable):
for element in iterable:
if not element:
return False
return True
I try to create a shorter algorithms to guess if a number is a prime-number or not
So there is the algorithms that I want to short
def is_premier(n):
i=2
while i < n and n%i !=0:
i+=1
return i==n
And there is what I try to do:
def is_prime_v3(n):
return ("Non Prime" if n%i==0 else "Prime" for i in range(2,n))
But I don't know if this generator is correct or there is a way to get the string ?
My real interest is not the prime number algorith, I try to figure out if is it possible to get something
with this following structure ( return a if condition else b for x in range(n); and collect the answer a or b)
Thanks for answers
You didn't manage to translate the first function correctly, no.
The function is_premier() returns a single boolean value, while is_prime_v3() returns a generator of strings.
The is_prime_v3() generator produces multiple "Prime" values for non-prime numbers, e.g. for 8, the test 8 % 3 == 0 is false, so "Prime" is generated:
>>> list(is_prime_v3(8))
['Non Prime', 'Prime', 'Non Prime', 'Prime', 'Prime', 'Prime']
Using a conditional expression is the wrong tool here. The first function stops early when a condition is met, while your second loop never stops early, and only produces different values each iteration.
If you use a regular loop and print() calls instead of yielding, this is what is executed:
for i in range(2, n):
if n % i == 0:
print("Non Prime")
else:
print("Prime")
That loop also never stops when n % i == 0 is found.
Now, it could have been your goal to do so, to produce Non Prime and Prime strings. However, it is easier if you used booleans instead, so True and False.
Your first function could be described, in English, as doing this:
Start i at 2
as long as i is smaller than n and n % i != 0 is true, add one to i.
if i is equal to n, we have a prime number!
You could also use a range() for that, and then it becomes:
Take i from the range 2 to n (not including n).
if ever n % i == 0 is true, this is not a prime number.
if we never found a value for i where n % i == 0, we have a prime number!
In code that is:
for i in range(2, n):
if n % i == 0:
return false
return true
For that kind of 'early exit' if a condition is met or not met, you can use the any() or all() functions. These work best with a generator, they test each value produced and return true or false early if the condition no longer holds.
E.g. for the case where all values of i must not be a divisor, you can use:
def is_prime_generator(n):
return all(n % i != 0 for i in range(2, n))
Finally, your own attempt, is_prime_v3(), could be made to do the same, if used as a utility function, where we don't require that all n % i != 0 tests are true, but that all strings are 'Prime':
>>> all(s == 'Prime' for s in is_prime_v3(8))
False
>>> all(s == 'Prime' for s in is_prime_v3(7))
True
Your direction is good, but your expression returns a series of strings instead of a single value.
Looking at your original code, it basically says: if any number less than n divides n - return False. Otherwise True.
So this directly translates to Python as:
def is_prime(n):
return not any(n%i == 0 for i in range(2,n))
Which is also equivalent to:
def is_prime_v3(n):
return all(n%i != 0 for i in range(2,n))
If you want to reproduce the same logic (i.e. i advances up to n stopping on first divisor), you could formulate it like this:
def is_prime(n):
return "Prime" if next(i for i in range(2,n+1) if n%i == 0) == n else "Non Prime"
or you could let the next() function select the string for you:
def is_prime(n):
return next(("Non Prime" for i in range(2,n) if n%i == 0),"Prime")
This question already has answers here:
What is Truthy and Falsy? How is it different from True and False?
(8 answers)
Closed 2 years ago.
Okay, so here is a piece of code. The function of the code is to take a value and determine whether or not it is odd or even.
def isEvenOrOdd(num):
return 'odd' if num % 2 else 'even'
Now my question lies in why this works. The way I am currently looking at this, is that --
num%2 returns a value. If num is 3, then num%2 = 1.
Why would the value of '1' satisfy the 'if' condition?
I assumed this was a matter of 1 and 0, but I tried the same code with %4, and if 3 is returned, it still satisfies the if statement.
I understand this may be a basic question for some, so my apologies for perhaps being slow in understanding this. Thank you!
Thank you for your help ! I actually understand it now
The reason has to do with the "truthy-ness" of objects in Python. Every object in Python, even if it's not a boolean value, is considered "truthy" or "falsy". In this case, an integer is considered "truthy" if and only if it is not zero.
Therefore, if the number is odd, its modulus will be 1 which is considered true. Otherwise, the modulus will be 0 which is considered false.
If you switch the modulus to 4, the result will be truthy iff the remainder is not zero (i.e., if the number isn't a multiple of 4).
in python the, some data types has a true value or a false value, it doesn't have to be a boolean.
for example
test = None
if test:
print("working")
else:
print("Not working")
you will notice you get an ouput of Not working the reason is for object None is regarded as False same applies for some other data type , for integer, as long as a value is zero (0) it will take it as False
So in your case, if num % 2 return 0 then you will have
'odd' if 0 else 'even' # will will return 'even'
This question already has an answer here:
Recursive code returns None [duplicate]
(1 answer)
Closed 6 years ago.
I created this function to return the closest prime to x (equal or above):
def primo(x):
i=2
prime=True
if x>=0:
while i<=x**(1/2) and prime==True:
if x%i==0:
prime=False
else:
i+=1
if (prime==True or x==2 or x==3) and x>1:
return x
else:
primo(x+1)
else:
primo(x+1)
But it only returns when x is already prime.
I have tried to put a print(x) on the same line as the return, but if x is not prime (12, for example), it only prints the number at the end, it does not return the value.
I would like the code to return the prime in every case, most especially if x is not prime (it would go around the code until x is prime).
Thanks.
You need to return the value of your recursive function call
else:
return primo(x+1)
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am having trouble understanding the shorthand conditional statement in the python below.
def number(number):
return number or number == 3
print number("")
What does this shortcut syntax mean? Is it the same as the following?
def number(number):
if number or number == 3:
return number
print number("")
The first prints False and the latter None (I believe None means the syntax is not valid?).
The conditional statement is a bit pointless in this case (except for some very strange cases like overwriting the equals/integer/boolean values of number).
Basically what you are doing right now is like this:
def number(number):
if number:
return number
else:
return number == 3
If there would be an and it would be useful, right now it's pointless.
The or can be useful like this:
return spam or eggs
If spam is not null it will return spam, otherwise it will return eggs.
Illustration btw:
>>> for number in range(5):
... print 'number', number, number or number == 3
number 0 False
number 1 1
number 2 2
number 3 3
number 4 4
Long version of number and number == 3 or 5
def number(number):
if number and number == 3:
return 3
else:
return 5
The spam and spam.eggs thing is useful because if spam would be None it wouldn't execute the spam.eggs part which would normally give an AttributeError.
The relevant expression in both cases is number or number == 3.
Python splits this expression into 2 parts: (number) or (number == 3)
It evaluates the individual parts first, and then evaluates the results with or.
So we have "" (treated as False) or "" == 3 (which evaluates to False).
This becomes "" or False. Since both expressions are False-y, this entire expression evaluates to False.
In the first function, you return the value of the expression, which is False.
In the second function, you only return the value of the expression if it is true. If it's false, you don't return anything.
In python, a function which doesn't return anything returns None by default.
If number is valued to True (So, not 0 or None), the function just returns the number.
If the number is valued to False, the function will return number == 3 (So True if it's 3, False else)
As the latter will always return False (If number == 3, then the function would have returned 3 in the first case), it could be shortened down to:
return number or False
Which will return the number if it's not 0 or None, else it will return False.
It has to do with how Python evaluates expressions and objects.
Your first example:
You send in a empty string "", this to Python is False, much like an empty list ([]).
def number(number):
# so this will now be (False) or (number == 3) but since the first
# expression was False it will not evaluate the number comparison and thusly
# return False
return number or number == 3
print number("")
Your second example is a otherwise.
You have an explicit if stating that if numbers evaluate to True ie. not empty or numbers are equal to 3 enter the following block and return from it.
But since you supply an empty string, which we just learned returns False, it will by pass the if and return the default value for any Python function, None.
def number(number):
if number or number == 3:
return number
#default says return None here.
print number("")