SETS 5. Using the IDLE Command Shell, type the statements in bold below(press enter after each statement). Save the enti
Posted: Sun Jul 03, 2022 11:23 am
SETS 5. Using the IDLE Command Shell, type the statements inbold below(press enter after each statement). Save the entire fileas setSample.py >>> set1=set() An empty set is created.Enter the statement below and press Enter to view the contents ofthe set. >>> set1 set() Like appending things to a list,you can add things to a set using the add method: >>>set1.add(1) The integer value 1 is added. If we now view the set,we can see that it contains the value 1. >>> set1 {1}There isn’t much difference between a set and a list. However, setscan hold only one copy of each possible value; that is, sets cannothold multiple items of the same value. Try to add the value 1again: >>> set1.add(1) If the variable set1 was referringto a list, a second value of 1 would be added. However, if we viewthe contents of set1 we’ll find that it has not changed:>>> set1 {1} If we add a different value, it is added tothe set. Enter the following two statements to add the value 2 tothe set and then view the contents of the set. >>>set1.add(2) >>> set1 {1, 2} Using curly braces to enclosea set of values to be added. Create another set with the name set2.>>> set2={2,3,4,5} >>> set2 {2, 3, 4, 5} A sethas methods that can work with other sets. Let’s look at thedifference method. >>> set1.difference(set2) {1} In thestatement above, the difference method is running on the objectreferred to by set1 and returns a set that contains all the itemsin set1 but not in set2. We can run the same method on set2 to findall the items in set2 that are not in set1. >>>set2.difference(set1) {3, 4, 5} The union method returns a set thatcontains all the elements of both sets: >>>set1.union(set2) {1, 2, 3, 4, 5} The intersection method returns aset that contains all the elements the sets have in common:>>> set1.intersection(set2) {2} The only element in set1and set2 is the element 2. We can also use methods on sets tocompare their contents. The isdisjoint method returns True if thetwo sets have no elements in common: >>>set1.isdisjoint(set2) False The two sets are not disjoint becausethey both contain the value 2. The issubset method returns True ifone set is a subset of the other (meaning one set is containedentirely within another set). Let’s create a new set to experimentwith this. >>> set3={2,3} >>> set3.issubset(set2)True This is True because set2 (which contains {2,3,4,5}) containsall the elements in set3. The issuperset method returns True if oneset is a superset of the other: >>> set3.issuperset(set2)False This is False because not all the elements in set3 are inset2.