Creating a new list from two other lists

  • Comp Sci
  • Thread starter ver_mathstats
  • Start date
  • Tags
    List
In summary: NotIn(n, list): # the same principle as IsPrime, but you test whether the number is not in the list for item in list: if item not in n: result=result and not result in list
  • #1
ver_mathstats
260
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.
 
Physics news on Phys.org
  • #2
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 __________________
 
Last edited:
  • #3
ver_mathstats said:
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.
 
  • Like
Likes sysprog and jedishrfu
  • #4
What numbers are in list2?

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))
 
Last edited:
  • Like
Likes Nick-stg
  • #6
Mark44 said:
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'.
 
Last edited:
  • #7
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 ' != ' ?
 
  • Like
Likes jedishrfu
  • #8
pbuk said:
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.
 
  • Like
Likes pbuk
  • #9
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.
 
Last edited by a moderator:
  • Like
Likes Nick-stg
  • #10
@original poster ver_mathstats
It is worth pointing out that in Python one doesn't use:
Code:
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)
 
  • Like
Likes jedishrfu
  • #11
@Merlin3189
Merlin3189 said:
Code:
for each number in list1:
"for each" is not valid python. It should read:
Code:
for number in list1:
 
  • #12
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. )
 
  • Like
Likes jedishrfu
  • #13
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
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.
 
  • #15
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.

Thank you all for contributing here.
 
  • Like
Likes jim mcnamara

FAQ: Creating a new list from two other lists

1. What is the purpose of creating a new list from two other lists?

The purpose of creating a new list from two other lists is to combine the elements of the two lists into a single list. This can be useful for organizing and manipulating data, as well as for performing calculations or comparisons.

2. How do you create a new list from two other lists?

To create a new list from two other lists, you can use a built-in function such as "concat" or "extend" in programming languages like Python. These functions allow you to merge two lists together and create a new list with all of the elements from both lists.

3. Can you create a new list from two lists with different data types?

Yes, you can create a new list from two lists with different data types. However, it is important to note that the resulting list will contain elements of both data types. If you want to create a new list with a specific data type, you may need to convert the elements of the original lists before combining them.

4. Is it possible to create a new list from two lists with duplicate elements?

Yes, it is possible to create a new list from two lists with duplicate elements. The resulting list will contain all of the elements from both lists, including any duplicates. If you want to remove duplicate elements, you can use a function or method to do so after creating the new list.

5. Are there any limitations to creating a new list from two other lists?

There are not many limitations to creating a new list from two other lists. However, it is important to consider the size and complexity of the lists, as well as the available memory and processing power of the computer or device you are using. In some cases, combining large or complex lists may take longer or require more resources.

Similar threads

Replies
2
Views
818
Replies
4
Views
1K
Replies
1
Views
1K
Replies
2
Views
4K
Replies
15
Views
3K
Replies
17
Views
1K
Replies
5
Views
2K
Back
Top