My For loop won't iterate through a list - python

I have to determine if all the numbers in a list are prime numbers and then return a boolean "True" or "False" statement depending on the outcome. I made some conditional statements inside of a for loop to see if the number was prime or not.
Here's the code:
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
break
elif (i % 2 == 0) and (i % i == 1):
is_prime = False
return is_prime
break
else:
is_prime = True
return is_prime
The problem is, and I saw this in the Python Visualizer, the for loop stops iterating after checking the first value in the list. I don't understand why as the syntax is the same as for loops I've used in the past.
I plugged in some example values like: all_primes([5,2,11,37]) or all_primes([5,2,4,37]) and the return value is always true since 5 is the first number on the list and the only number that is being iterated.
Any ideas as to why?

You have a return and a break in your if/else block, you should get rid of them. Also the return in the else should be outside, or it will just return whenever he finds a "prime".
def all_primes(xs):
is_prime = None
for i in xs:
if i < 2:
is_prime = False
return is_prime
elif (i % 2 == 0):
is_prime = False
return is_prime
else:
is_prime = True
return is_prime
After this, you should know, that you are not really checking primes.
Here is not the most efficient way but its clear how to:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
return all(map(checkPrime, xs))
EDIT:
without the map functions, you just have to iterate with a for loop:
def all_primes(xs):
def checkPrime(n):
if n < 2:
return False
for i in xrange(2, n):
if n%i == 0:
return False
return True
for n in xs:
if not checkPrime(n):
return False
return True

You should see the problem the other way around.
If you you find a number which is not prime you should return False, and after your loop end you should return True.

Related

How to properly check if a number is a prime number

Hey so i have this function to check if a number is a prime number
def is_prime(n):
flag = True
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag
print(is_prime(1))
However when i test the number 1, it skips the for loop and returns True which isn't correct because 1 is not a prime number.
How could i fix this?
You can first start by checking if n is greater than 1 the code should proceed, else it should return False. If n passes the first condition, only then the code can proceed to verify if n is indeed prime or not.
def is_prime(n):
flag = True
if n > 1:
for i in range(2, n ):
if (n % i) == 0:
flag = False
return flag # Returns this flag after check whether n is prime or not
# Returns False if n <= 1
return False
print(is_prime(1))
output:
False
2 is also skipped by the loop, but the function returns true thanks to the flag, and we know that's right.
Also you can exit early the loop if the condition is met:
def is_prime(n: int) -> bool:
if n > 1:
for i in range(2, n): # if n == 2, there is no loop, is never checked
if (n % i) == 0:
return False # can return early once we meet the condition, don't need to finish the loop
return True
print(is_prime(7534322224))
print(is_prime(5))
An alternative approach (though much slower on bigger numbers):
def is_prime(n: int) -> bool:
if n < 2: return False
return n == 2 or True not in [True for i in range(2, n) if (n % i) == 0]
print(is_prime(75343224))
print(is_prime(5))

Writing a function that checks prime numbers

def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
break
else:
return True
Im trying to make a function that checks if an input is prime or not. This code does return True if I enter a prime number, but it also enters true whenever I enter a multiple of a prime number? Why is this happening
thanks
The problem with your code is that you have return statements in the first iteration of the loop. Also break statement is not needed. Moving return True outside the loop gives the solution:
def primecheck(num):
for i in range(2, num):
if num % i == 0:
return False
return True
I leave num = 0 or 1 for you.
Or you can simply use for else for this.
def primecheck(num):
if num>1:
for i in range(2, num):
if num%i==0:
return False
break
else:
return True
print(primecheck(15))
The problem is with your else statement, no need for it. And also break is not needed
def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
return True
or you can solve it without any iterations. You can use Fermat's little theorem to solve this easily(hope you refer it),
def primeChecker(n):
m = 2 #can be any number
if(n > 1):
if (((m**n)-m)%n == 0): #Using Fermat's little theorem
return True
return False
n = int(input());
if primeChecker(n):
print('{} - is prime number'.format(n))
else:
print('{} - NOT a prime number'.format(n))
Doing a little research on the internet will help to solve these types of questions much easier and efficiently. ;). Cheers!
You are using return in the else part. So your code will break after 1st iteration and print the result of first iteration.
You can do something like this:
def primecheck(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
return False
return True
print(primecheck(15))

determining if random Int is prime or not

I have a little problem when i need to determine if a number , x is a prime number or not.
x will be a randomly generated positive integer and i get the following message when i execute code:
Your function fails on is_prime(2). It returns None when it should return True.
My code:
def is_prime(x):
if x < 2:
return False
else:
for n in range(2, x):
while x % n == 0:
return False
break
else:
return True
i want the while loop to iterate through n == 2 up to n == (x-1) but it doesnt seem to do it!
what am i doing wrong?
You could write this function much more simplier:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
So your call for is_prime(2) wouldn't pass the if test and wouldn't be used in the for run and would just return True.
All other prime numbers should be tested if they are greater than 3 and not even.

My is_prime function fails on 9, and I don't know why?

I have a bit of a problem. I am writing an is_prime function on, but whenever I run it, it fails on is_prime(9), and I cannot see why:
def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
else:
return True
it returns True for some reason on is_prime(9)?
That is because the function does not check all eligible divisors until it returns.
Instead, it exits early with True if x is not divisible by 2, which is not what you want for odd numbers (e.g. 9 is not divisible by 2, yet it's not prime).
Instead, you want to try all possible divisors from 2 to x-1, and then return if x is divisible by none of them.
To do so, rewrite as such:
def is_prime(x):
if x < 2: ##because negative numbers, 0 and 1 are not prime##
return False
elif x == 2:
return True
else:
for n in range(2, x):
if x % n == 0:
return False
return True

Python primes function giving incorrect output

I have been asked to create two functions, the first is_divisible(n,primes) to check if a number is divisible by any other numbers in prime
and then the second which would use the first to find all the prime numbers in a particular range.
I don't know why, but i cannot work out how to get the primes to show. Anything obvious about what I am doing wrong?
def is_divisible(n, primes):
for p in primes:
if n % p == 0:
return True
else:
return False
def find_primes(N):
primes=[]
for n in range(2, N+1):
is_divisible(n,primes)
if False:
primes.append(n)
print(primes)
find_primes(20)
def is_divisible(n, primes):
for p in primes:
if n % p == 0:
return True
return False # Only return False if no matches
def find_primes(N):
primes=[]
for n in range(2, N+1):
if not is_divisible(n,primes)
primes.append(n)
print(primes)
print find_primes(20)
This if statement will never be true:
if False:
primes.append(n)
Rewrite the code like this:
if is_divisible(n,primes)==False:
primes.append(n)
This code is wrong:
is_divisible(n,primes)
if False:
primes.append(n)
You should check if the divisibility inside the if condition. Try this:
if not is_divisible(n,primes):
primes.append(n)
Python evaluates 0 to False, and all numbers otherwise.
So, it's not necessary to do something like "if condition == True". Use just if condition.

Categories