In: Computer Science
C++, Java, Python. Assume we have two sequences of values S1 containing 1, 5, 3, 6, 7, 8 while S2 containing 2, 5, 6, 9, 7. We’d store these two sequences as sets and performance set intersection and set difference. Write C++, Java, Python codes to do that respectively. Compare and contrast the readability and writability.
CODE IN PYTHON:
# IF YOU WANT TO TAKE SET INPUT FROM USER:
set1=set([int(value) for value in input().split()])
set2=set([int(value) for value in input().split()])
#INTERSECTION
# methods for the intersection between two lists or set
#method 1: (intersection means a value is present in both sets)
lst1=[1,5,3,6,7,8]
lst2=[2,5,6,9,7]
lst3=[value for value in lst1 if value in lst2] # lst3
hold the intersection of lst1 and lst2
print("intersection of two list lst1 and lst2:")
print(lst3) #simply print insection list:
#output:
the intersection of two list lst1 and lst2:
[5, 6, 7]
#method 2:
set1=set([1,5,3,6,7,8]) #convert list in to set because set never
have repeated values but list can hold repeated values.
set2=set([2,5,6,9,7])
set3=set1.intersection(set2)
print("intersection of two set set1 and set2:")
print(set3)
#output:
intersection of two set set1 and set2:
{5, 6, 7}
#DIFFERENCE
#methods for difference between two list or set
# method 1:(difference means a value is present in one set but
not present in another set )
lst1=[1,5,3,6,7,8]
lst2=[2,5,6,9,7]
lst3=[value for value in lst1 if value not in lst2]
print("difference of two list lst1 and lst2:")
print(lst3)
#output:
the difference of two list lst1 and lst2:
[1, 3, 8]
# method 2:
set1=set([1,5,3,6,7,8])
set2=set([2,5,6,9,7])
set3=set1.difference(set2)
print("difference of two set of lst1 and lst2:")
print(set3)
#output:
difference of two set of lst1 and lst2:
{8, 1, 3}
... I think I have to explain everything very clearly. you can check this code by running.