Sunday, August 5, 2018

Lesson-6 : Sets and Frozen Sets

This blog assumes that you have a Linux machine with Python already installed. 
If you don't, then you can use an AWS cloud based image that has Python. For help, refer to my blog
I am using Python 2.7 for this tutorial.

SETs

Set is a data type created to emulate the mathematical concept of sets. 

Def: Set is an UNORDERED collection of UNIQUE objects.

Sets do not support indexing. Meaning a single object of a set cannot be accessed.


Example Program - 8:
**************************************************************
#! /bin/python

a = set ([1,2,3,4])

b = set(['Harsha',2,3,"string1"])

c = a & b # Intersection. 

d = a | b  # Union

e = set([2,3,3,4,4,5,6])

print "\n a = ", a
print "\n b = ",b
print "\n c = ",c
print "\n d = ", d
print  "\n e = ",e  # Check out the output. 

f = a.intersection(e)   # This is equivalent to  f = a & e

print "\n f  = ",f

a.add("Numbers")  # Adds the object to the set
a.discard(4)            # Removed the object from the set

print "\n a = ",a

g = a - b  # Difference.

print "\n g = ",d

**************************************************************



EXERCISE - 5

Write a program that has at least 4 sets and performs all set operations including comparison. Ex: Is set A super set of set B?


FROZENSETs


A frozen set is an IMMUTABLE set. 

Syntax is : 

a = frozenset([1,2,3])

The add method is not available on frozensets.





EXERCISE - 6

Write a program with frozensets and explore what can and cannot be done with them. Do a bit of research :) 


Lesson-6 : Sets and Frozen Sets

This blog assumes that you have a Linux machine with Python already installed.  If you don't, then you can use an AWS cloud base...