The discussion focuses on creating a new list from two existing lists while incorporating a prime number condition. Participants highlight the importance of ensuring both lists are of equal length to avoid index errors and suggest using a primality test function, such as trial division, to check if numbers are prime. The Sieve of Eratosthenes is mentioned as a prime number generator but clarified as not suitable for individual primality testing. Additionally, proper iteration techniques in Python, such as using `zip()` for parallel list processing, are discussed. The conversation concludes with a reminder to stay focused on the original problem rather than diverging into broader programming language debates.
#1
ver_mathstats
258
21
Homework Statement
Let list1 and list2 be two given lists of integers. Write a Python code to create list3, the list whose elements are the elements of list1 which are prime numbers and do not belong to list2.
Relevant Equations
Python
Code:
list3=[]
for i in range (len(list1)):
list3.append(list1[i])
list3.append(list1[i]=!list2[i])
I was just wondering if I am on the right track with this question. I also am confused as to how to incorporate the prime number condition into my code. Thank you, any help is appreciated.
It seems that you are except you have made an assumption that list1 has the same number of elements as list2.
Two things could happen:
1) no error when list1 is less than list2 element-wise but the results are incomplete (the bane of programmers).
2) array index error on list2 when list1 is greater than list2 element-wise. (programmers hate index out-of-bounds data dependent errors at runtime)
I think you may need to step through your algorithm on paper to see where it fails:
Code:
for each element of list1:
1) is it a prime number?
-- if not a prime then _________
-- else _________
2) is it a member of list2?
-- if yes then ____________
-- else __________________
I also am confused as to how to incorporate the prime number condition into my code.
You'll need to include some code; i.e., write a function, that determines whether a given number is prime. Possibly the simplest algorithm is the Sieve of Eratosthenes (a web search should turn up lots of hits).
The basic idea is that, for a given number n, you need to divide ##M = \sqrt n## (can truncate this to an integer) successively by 2, 3, ..., M. If the remainder after division for any of these divisors is 0, then your number is composite, and thus not prime. The Python modulus operator, %, can be used to find the remainder after integer division.
For example, let n = 37. ##M = \lfloor \sqrt{37}\rfloor = 6##.
37 % 2 == 1
37 % 3 == 1
37 % 4 == 1
37 % 5 == 2
37 % 6 == 1
So 37 is prime, since none of the remainders was 0. Note that you can use the Python modulus operator, %, to find the remainder.
The usual way to create a list of prime numbers is to use the modulo operation.
As an example:
Python:
prime_list=[]
for i in range(2,100): ## starts at 2 and skips 1 since 1 isn't prime
nfactors=0
for j in prime_list:
if ( (i % j ) == 0): ## if mod zero then j is a factor of i eg 10%2 = 0 and 10%5 = 0 hence 2,5 are factors of ten
nfactors+=1
if(nfactors==0): ## we found a prime number ie has no factors in the plist
prime_list.append(i)
for p in prime_list:
print(""+str(p))
You'll need to include some code; i.e., write a function, that determines whether a given number is prime. Possibly the simplest algorithm is the Sieve of Eratosthenes (a web search should turn up lots of hits).
...
I think you are mis-remembering the algorithm for the Sieve of Eratosthenes which is a prime number generator, not a primality test. The primality test algorithm you describe is usually referred to as 'trial division'.
Aside from the prime issue, which I assumed you'd not yet started on, it appears to me that you are not checking whether each item in list 1 is in list 2, rather whether items in list 1 are the same as the corresponding position item in list 2.
So that list1 [ 5, 4, 3, 9, 8,7] and list2 [ 2, 3, 4, 5, 6, 7 ] would give list3 [3, 5 ]
And I don't think ' =! ' is acceptable. Do you mean ' != ' ?
I think you are mis-remembering the algorithm for the Sieve of Eratosthenes which is a prime number generator, not a primality test.
You're right -- I've misremembered what the Sieve is supposed to do. Rather than what I said, it is supposed to successively remove multiples of 2, then of 3, 4, and so on. What I was thinking of was a primality test.
I guess you've solved your problem by now, but just thought I'd give my take on how to approach this sort of problem.
You want to find numbers in list 1 that are prime and not also in list 2, so
Python:
list3=[]
for each number in list1:
if IsPrime(number) and NotIn(number, list2): # I'd check the other way round, but I stuck to Q order
list3.append(number)
Then all you have to do is write the functions IsPrime(), NotIn() and rewrite the pseudocode in clean Python.
NotIn() turns out to be a built in operator, <number> not in <list>
IsPrime is easy, because you can find n+1 examples in Python tutorials, but otherwise you iterate the same way: you divide the number by each smaller number and see if any have no remainder
Python:
def IsPrime(n):
result=True # assume it's prime until you find a factor
for factor in range(2, n): # you don't need to go up to n-1, but it keeps code simple for a start.
if Remainder(n,factor)==0: # found an exact factor
result=False # you could break loop now, as you know it's not prime
return result
Again, Remainder() is a thing in Python, otherwise you'd iterate again, or think of another formulation for this line.
Not the most efficient way of coding, but I find it easy to understand what I'm doing and programs are easy to test by writing cheat functions until you work them out properly. (Eg. if you haven't written an IsPrime() function, just make it, "if in [2,3,5,7,11,13,17,19]" while restricting your test data up to 20. )
When you do write each function, you can test it standalone in interactive mode.
You only get stuck if you can't think of any algorithm, but then you're stuck however you approach it. (So go on PF and ask about suitable algorithms.)
Sorry for poor layout. I haven't used code formatting on PF before.
for i in range(len(list1)):
print(list1[i]) #prints 1, then 2, then 3 etc...
Instead one iterates on the list istelf:
Code:
list1 = [1,2,3,4,5]
for elem in list1:
print(elem) #prints 1, then 2, then 3 etc...
Also to iterate through two lists at the same time, that is element 1 of list1 and list2 then, element 2 of the lists etc. You can use zip(). It should be noted that if the lists are not of the same length the iteration will stop when the length of the shorter list is reached. Example:
Code:
list1 = [1,2,3,4,5]
list2 = [a,b,c,d,e]
for elem1, elem2 in zip(list1, list2):
print(elem1, elem2) #prints 1 a, then 2 b, then 3 c etc...
If you need to iterate to the end of the longer list then you would need to use itertools, exactly how I don't know off the top of my head, and I doubt it is relevant in this case. You can look it up if you are interested. As to the rest of the problem, as a result of the many other valid comments I'm not sure what it is you need to achieve.@jedishrfu
in your "Spoiler:Prime Code" what is plist? (in the second for loop)
Yes. I consciously did that as I was trying to write pseudocode rather than give the Python code.
I suppose I should have used { } or begin ... end after the ifs to avoid giving the impression that it already was Python, but if they've only done Python, that might be confusing? (I understand that some schools here teach Python as a first language. I can't quite believe it. I'd rather have to teach C as a starter. I think Python is the most difficult language I've ever tried. )
With respect to C, it is far more difficult for beginners. The problem is that pointers crop up everywhere and students working alone get caught not even knowing what went wrong. I know because I taught it to a bunch of engineers at a company education center and the mess they would get into was quite fascinating.
My problem with Python has been the tabbing issue where it balks when tabs are used versus spaces. I now use spaces exclusively. Another issue has been the transition from 2.7 to 3.x where division by integer operation changed and broke working 2.7 code.
But let’s not derail the conversation here over which language is best. The OP has a specific problem to solve using Python and that’s the focus of this thread.
#14
Nick-stg
35
29
The "Spoiler:Prime Code" is nice, I would add one refinement. I would add a break at if (i % j ) == 0:. This will stop the loop through the prime_list, one factor is enough to know it's not prime. But this is nit-picking and beyond the scope of the OP's assignment.
Since the OP got his answer, its time to close before we devolve the thread into discussions of python, primality... marginally related to the topic at hand.