I'm trying to create a program which checks if the number is a prime number. My idea was to use the function that the square root of the number, divided by all numbers up to the square root defines if the number is a prime or not. (I hope you understand)
Anyway, I'm trying to find a way to use modulus on every character in my list. As an example
Prime % List(2,sqrtPrime) =/ 0 #I know this doesnt work, just a hint how i want it to work.
As the error if I run this is that I cant use modulus on a list, so how do i do it?
And also, will this idea go through every character from 2-sqrtPrime?
Thanks
What seems the optimal way to me, would look like:
rng = xrange(2, int(math.sqrt(n)) + 1)
is_prime = all(n % i for i in rng)
Main points are:
rng is a generator, not a list
expression within (...) is a generator as well, so no unnecessary intermediate lists are created
all will stop iterating as soon as the first divisor is found, thus no extra iterations
You could write a function that returns True if its argument is Prime and otherwise False, then run filter on the list.
import math
def isPrime(x):
for factor in range(2,math.floor(x**0.5)+1):
if x % factor == 0:
# x divides evenly, so
return False
return True
lst = [some, numbers, go, here]
primes_in_lst = filter(isPrime, lst)
Or if you're against filter as a rule (some people contend it's unpythonic) then you can put it in a list comp.
primes_in_lst = [num for num in lst if isPrime(num)] # exactly equivalent
and technically that isPrime function could be a lambda:
primes_in_lst = filter(lambda x: all(x%factor for factor in range(2,math.floor(x**0.5)+1)), lst)
But jeebus that's ugly.
Related
There's a working isPrime function that takes in one argument and returns true if the number is prime and false if otherwise. How can I create a generator to print out each prime numbers that go through the isPrime function?
This is what I tried but I'm positive it doesn't work.
primeGen = [var for var in isPrime(var) if isPrime(var)]
print(primeGen)
Any pointers would be appreciated!
My approach would be
def primeGen(start=1):
while True:
if isPrime(start):
yield start
start += 1
Usage
pg = primeGen()
for i in range(10):
print(next(pg))
First of all, I see from isPrime(var) that it returns true or false how can you use it in for loop, this doesn't make sense. Do something like this if you need a list for Prime number until n.
primeGen = [var for var in range(n) if isPrime(var)]
print(primeGen)
The biggest problem here is that you need some sort of iterator that starts at 1 and goes to infinity. Thankfully, itertools provides one. We can use it to create a generator:
import itertools
...
primeGen = (n for n in itertools.count(start=2, step=1) if isPrime(n))
type(primeGen) # <class 'generator'>
# do not do the following:
for i in primeGen:
print(i)
# this continues infinitely
which will successively output prime numbers, in sequence.
Note that I use () here instead of []. What we want is a generator, not a list comprehension - using the square-brackets will freeze the program, because it tries to build the entire list before returning it, and there is no end to infinity. Using () returns a generator instead of a list, which is fine.
I'm trying to make a program that involves checking if a number's modulus is zero for every number in a list, and then, if it's modulus of all of them is zero, it adds it to the list. Like this:
nums = [1,2,3,5]
if( var1% *Everything in nums* ==0):
nums.append(var1)
If you're wondering, It's for calculating primes. Thanks in advance.
There is a function called all for this kind of thing.
nums = [1,2,3,5]
if all(var1%n==0 for n in nums):
nums.append(var1)
I have a list:
l = [1,3,4,6,7,8,9,11,13,...]
and a number n.
How do I efficiently check if the number n can be expressed as the sum of two numbers (repeats are allowed) within the list l.
If the number is in the list, it does not count unless it can be expressed as two numbers (e.g for l = [2,3,4] 3 would not count, but 4 would.
This, embarrassingly, is what I've tried:
def is_sum_of_2num_inlist(n, num_list):
num_list = filter(lambda x: x < n, num_list)
for num1 in num_list:
for num2 in num_list:
if num1+num2 == n:
return True
return False
Thanks
def summable(n, l):
for v in l:
l_no_v = l[:]
l_no_v.remove(v)
if n - v in l_no_v:
return True
return False
EDIT: Explanation...
The itertools.cominations is a nice way to get all possible answers, but it's ~4x slower than this version since this is a single loop that bails out once it gets to a possible solution.
This loops over the values in l, makes a copy of l removing v so that we don't add v to itself (i.e. no false positive if n = 4; l = [2, 1]). Then subtract v from n and if that value is in l then there are two numbers that sum up to n. If you want to return those numbers instead of returning True just return n, n - v.
Although you can check this by running through the list twice, I would recommend for performance converting the list to a set, since x in set() searches in linear time.
Since n can be the sum of the same number, all you have to do is iterate through the set once and check if n - i occurs elsewhere in the set.
Something like the following should work.
>>> def is_sum_of_numbers(n, numbers):
... for i in numbers:
... if n - i in numbers:
... return True
... return False
...
>>>
>>>
>>> numbers = {2,7,8,9}
>>> is_sum_of_numbers(9, numbers) # 2 + 7
True
>>> is_sum_of_numbers(5, numbers)
False
>>> is_sum_of_numbers(18, numbers) # 9 + 9
True
If the list is ordered you could use two variables to go through the list, one starting at the beginning of the list and one at the end, if the sum of the two variables is greater than N you assign to the variable at the end the values that precedes it, if the sum is less than N you assign to the variable at the beginning the following value in the list. If the sum is N you've found the two values. You can stop when the two variables meet eachother.
If the list is not ordered you start from the beginning of the list and use a variable x to go through the list. You'll need another structure like an hashset or another structure. At every step you'll look up in the second hashset if the value N-x is in there. If there is, you've found the two numbers that add up to N. If there isn't you'll add N-x in the hashset and assign to x the following value. I recommend using an hashset because both the operations of looking up and inserting are O(1).
Both algorithms are linear
I'm sorry I couldn't write directly the code in python because I don't use it.
As I said in the comment HERE there's a video in wich your problem is solved
If I got the OP's concern then-
As the question says repeats are allowed within the list l this process i think is good though a bit slower.So if you need to count the occurances along with the existence of a condition then go with this answer but if you want a bolean esixtence check the go with the others for the mere performance issue nothing else.
You can use itertools.combinations. It will give you all the combinations, not permutations. Now you can just use the sum function to get the sum.
from itertools import combinations
l = [1,3,4,6,7,8,9,11,13]
checks = [4,6] #these are the numbers to check
for chk in checks:
for sm in combinations(l,2):
if chk == sum(sm): #sum(sm) means sum(1,3) for the first pass of the loop
#Do something
Can someone explain why this code works with the sample number 13195, but crashes when I use the problem's number
num = 13195
def isprime(num):
for i in range(2,num):
if num % i == 0:
ans = i
return ans
print isprime(isprime(isprime(num)))
In Python 2, range constructs a list. So the program is trying to contain an enormous list in memory, and it can't. Use xrange which will generate the numbers on demand for iteration instead of all at once.
You also need to end the loop early or it will spend forever checking so many numbers. So once you find a divisor, use it to divide the original number and make it smaller and thus manageable.
You need to assign a default value to ans.
When the input number is a prime number, the program never assigns anything to the variable ans. So that, when the function tries to return that variable, it is not actually defined.
This question already has answers here:
How to create the most compact mapping n → isprime(n) up to a limit N?
(29 answers)
Closed 7 years ago.
I am new to Python and I'm attempting to write a code that checks to see whether or not a number is prime. So far, I've written this:
def main():
n = input("Enter number:")
isprime(n)
def isprime():
x = Prime
for m in range (1,n+1,1)
result = n % m
print result
main()
I'm not sure how to proceed after this. I know I have to define isprime. Any help would be greatly appreciated. Thank you!
Your first and biggest problem is that you need to list n as a parameter to isprime before you can use it within isprime, and before you can pass an argument in main. See the tutorial on Defining Functions for more details. But basically, it's like this:
def isprime(n):
Also, that x = Prime is going to raise a NameError, because there's nothing named Prime. Given that it doesn't actually do anything at all, you should just delete it.
Of course that won't make this a complete working prime testing function, but it is how to proceed from where you are.
The next step is to consider what to return from the function. If you find a value that divides n, then obviously n isn't prime, and therefore isprime is false. If you go through all possibilities and don't find anything that divides n, then isprime is true. So, with two return statements in the right places, you can finish the function.
Once it's at least always returning True or False, you have bugs to fix.*
Look at what numbers you get from range(1, n+1, 1). Two of those numbers are guaranteed to divide any n. How do you avoid that problem?
After you've got it working, then you can work on optimizing it. If you look up primality test on Wikipedia, you can see a really simple way to improve the naive trial division test. A bit of research will show the pros and cons of different algorithms. But if what you've got is fast enough for your purposes, it's usually not worth putting more effort into optimizing.
* You might want to consider writing a test program that calls isprime on a bunch of numbers and compares the results with the right answers (for answers you already know off the top of your head—1 is not prime, 2 is prime, 17 is prime, etc.). This is called Test Driven Development, and it's a great way to make sure you've covered all the possible cases—including outliers like 0, 1, 2, -3, etc.
Your isprime is quite close. The first line x = Prime is unnecessary, so let's get rid of that.
Now, let's take a look at what you're doing next:
You seem to want to check if there are any numbers that divide n perfectly. While this is the correct approach, you are including n and 1 in the numbers that you are testing. This is wrong for obvious reasons.
There is another error: you use n without ever defining it (I think you want it to be a parameter to your function). So let's put all this together:
def isprime(n):
for m in range(2, n):
if not n%m: # m divides n perfectly
return False
return True # if n were not prime, the function would have already returned
But going a step further, you don't really have to check every number between 2 and n-1. You just need to check the numbers between 2 and the square-root of n:
def isprime(n):
for m in range(2, int(n**0.5)+1):
if not n%m:
return False
return True