Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 4

84 bytes added, 22:15, 16 August 2017
PART 2 - Sets
:'''Perform the Following Steps:'''
:#Within your ipython3 shell, create a few sets to work with by issuing the following:<sourcelang="python">
s1 = {'Prime', 'Ix', 'Secundus', 'Caladan'}
s2 = {1, 2, 3, 4, 5}
'Geidi' in s1
</source><br>'''Sets can be combined''', but it is important to note that any '''duplicate values (shared among sets) will be deleted'''.<br><br>
:#Issue the following, and note the items (and values) that are common to the following sets:<sourcelang="python">
s2
s3
s2.union(s3) # same as s2 | s3
</source>Notice that both methods above provides the same result, but the first method requires less keystrokes.<br><br>Instead of combining sets, we can display '''values that are common to both sets'''. This is known in mathematical terms as an '''intersection''' between the lists.<br><br>
:#To demonstrate intersection between sets s2 and s3, issue the following:<sourcelang="python">
s2 & s3 # returns a set containing all values that s2 and s3 share
s2.intersection(s3) # same as s2 & s3
</source>
:#Sets can also have their values compared against other sets. First find out what items are in '''s2''' but not in '''s3'''. This is also called a '''difference'''. But notice that it only shows values that '''s2''' contains, specifically values that '''s3''' doesn't have. So this isn't really the <u>true</u> difference between the sets.<sourcelang="python">
s2
s3
</source>
:#In order to see <u>every</u> difference between both sets, you need to find the '''symmetric difference'''. This will return a set that shows all numbers that both sets do not share together.<br><br>
:#To demonstrate, issue the following:<sourcelang="python">
s2 ^ s3 # returns a set containing all values that both sets DO NOT share
s2.symmetric_difference(s3) # same as s2 ^ s3
:::10. To demonstrate, issue the following:<sourcelang="python">
l2 = [1, 2, 3, 4, 5]
l3 = [4, 5, 6, 7, 8]