Python coding help

profiletqomasjay10i7

  

Task 2

Given two lists, write python code to print “True” if the two lists have at least one common element. For example, x = [1,2,3], y=[3,4,5], then the program should print “True” since there is a common element 3.

Hint: 

We can first calculate set(x) - set(y). set(x) - set(y) is to remove the element in x that also exists in y (3 in this case). So set(x) - set(y) will be equal to (1,2), which is a set. And its length is 2 if you calculate len(set(x) - set(y)).

if set(x) - set(y) has a smaller length than set(x), i.e. len(set(x) - set(y))<len(set(x)), it means that some element in x is removed because that element also exist in y. Then we know there must be at least one element in common.

This will get easier after we learn the iteration structure and the conditional statement in the next few weeks. 

    • 6 years ago
    • 7
    Answer(1)

    Purchase the answer to view it

    blurred-text
    • attachment
      Assignment2.py
    • attachment
      Assignment2.docx