I'm doing a python challenge and I cannot go further...
I need to verify if the numbers in the vetor are primes.
Like:
vetor = [2,5,12]
2 is prime(TRUE)
5 is prime(TRUE)
12 not prime(FALSE)
This is my code until now:
vetor = [ ]
def is_prime():
x = vetor
if x == 1:
return False
elif x == 2:
return True
for i in range(x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
return is_prime()
print(number())
But doing this, Python returns me:
TypeError: 'list' object cannot be interpreted as an integer
What could I do to manipulate that data inside my list?
Try this:
vetor = [ ]
def is_prime(x):
if x == 1:
return False
elif x == 2:
return True
for i in range(1, x):
if (x % i) != 0:
return True
else:
return False
def number():
value = int(input('Write an integer number bigger than 1: '))
if value >= 1:
vetor.append(value)
return number()
elif value < 0:
return number()
elif value == 0:
for x in vetor:
if is_prime(x):
print(x, 'is prime')
else:
print(x, 'is not prime')
print(number())
You're trying to evaluate the value of a 'whole' list (datatype) against an integer (datatype) value (1 or 2), and then you're using the whole list as it were a single integer value again. You should address every single value in the list and check it separately.
You can do it, per example, with a for-each loop:
for value in vetor:
#do wahtever you want with 'value'
I would recommend making is_prime accept an integer as an argument. Then it's just a pure function that takes in an integer and outputs a boolean value.
I also notice a problem in your is_prime implementation. In your if-else statement, the function returns no matter what during that statement, so the for loop will always stop after only one iteration. You should only return False if all of the divisors you check do note divide the number:
import math
def is_prime(n):
if n <= 1:
return False
for d in range(2, int(math.sqrt(n))+1):
if n % d == 0:
return False
return True
# >>> is_prime(7)
# True
# >>> is_prime(8)
# False
I also think it would be clearer to write your program iteratively, rather than recursively (your number function currently calls itself). This might look like
vector = []
while True:
value = int(input('Write an integer bigger than 1: '))
if value == 0:
break
elif value > 0:
vector.append(value)
for n in vector:
print(n, is_prime(n))
# prints something like:
#
# 1 False
# 2 True
# 11 True
Related
I've worked a lot on this but I can't figure out the problem. Can you help me?
The code should print numbers from 0 to 100 and print next to the prime numbers "Prime". The first function works but if I try to print the numbers all togheter the "prime" tag gets misplaced.
def testPrime(numTest):
if numTest <= 1:
return False
if numTest == 2:
return True
for i in range(2, numTest):
if (numTest % i) == 0:
return False
else:
return True
def printPrimes (lenght):
i = 0
while i <= lenght:
if testPrime(i):
print(str(i) + "Prime")
else:
print(str(i))
i += 1
printPrimes(100)
The logic in testPrime() is flawed. There are faster techniques but here's a trivial approach that may help:
def testPrime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n % i == 0:
return False
return True
Since a prime number is defined a number a natural number greater than 1 that is not a product of two smaller natural numbers
I think this is the only lines you need.
def testPrime(n):
for i in range(2,n):
if n%i == 0:
return False
return True
This question already exists:
Checking if a number is prime in Python [duplicate]
Closed 2 years ago.
def is_prime(num):
lst = []
if num > 1:
pass
else:
return False
for number in range(0, 1000000+1):
if str(num) in str(number):
continue
elif str(1) in str(number):
continue
elif str(0) in str(number):
continue
lst.append(number)
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
print(is_prime(9))
I do not know what is the problem with my code and I cannot find a solution the point of the program is to check whether the number is a prime number or not(prime number is only divisible by 1 and itself). The for loop just doesn't seem to work or something
def isprime(n):
return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))
Output:
False
False
True
True
False
False
True
Or:
def isprime(n):
if n < 2: return False
for i in range(2, n):
if n % i == 0:
return False
else:
return True
Line 16-19:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
The first statement, num % num == 0 is finding the remainder when num is divided by num, which is always zero and therefore this statement is always true. num % 1 == 0 is also always true, so your code is equivalent to:
if not(num % x == 0):
return True
else:
return False
Which means, in the context of your program, "if the first value in lst is not a factor of num, then num is prime. Otherwise, num is not prime"
This only runs the loop one time and is backwards. Instead, you need to check if one of the numbers in lst is a factor to return False, and if all of the number is lst are not factors, then return True
for x in lst:
if num % x == 0:
return False
return True
for x in lst:
if num % num == 0 and num % 1 == 0 and not(num % x == 0):
return True
else:
return False
This loop can only ever run once, as it's guaranteed to return either true or false at the first iteration. If you find any factors, you want to return False. Otherwise, True.
for x in range(2, num):
if num % x == 0:
return False
return True
(Also, I'm not sure what was going on with the str shenanigans or the num % num / num % 1 conditions, both of which are always zero. But those should be unnecessary)
Except for 2 itself, you should only check divisibility by odd numbers up to the square root of the value.
Here's a short version:
def isPrime(N):
return all(N%p for p in range(3,int(N**0.5)+1,2)) if N>2 and N&1 else N==2
have 2 functions. first one generates a list and the second one checks if theres duplicates. if theres duplicates it returns True
so i want to call function 2 from function 1 and if it returns true do something
heres my code
import random
def x(list):
for i in range(len(list)):
count = 0
for k in range(len(list)):
if list[i] == list[k]:
count += 1
if count > 1:
return True
if count == 1:
return False
def generated_list(N):
list = []
for i in range(N):
list.append(random.randint(1, 365))
x(list)
if generated_list(25) is True:
print('is true')
There were some logical errors, check this one :
import random
def check_duplicate(numbers):
for i in range(len(numbers)):
count = 0
for k in range(len(numbers)):
if i == k:
continue
if numbers[i] == numbers[k]:
count += 1
if count > 1:
return True
return False
def generated_list(n):
numbers = []
for i in range(n):
numbers.append(random.randint(1, 365))
return check_duplicate(numbers)
if generated_list(25) is True:
print('is true')
Also, avoid reserved keyword for naming your variables.
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.
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