SETS AND MAPS
SETS AND MAPS
Sets:
A set is an unordered collection of items. Every set element is unique and no duplicates allowed.
• A set is a mutable. We can add or remove items from it.
• Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating a Set:
A set is created by placing all the elements inside curly brackets, { }, separated by comma or by using
built-in function set().
Syntax:
set_variable= {val1, val2, val3, ……}
(or)
set_variable= set ([val1, val2, ....... ]}
>>> s={1,2,3,5,9}
>>> s
{1, 2, 3, 5, 9}
>>> s1
Page 1
The Set Abstract Data Type
The Set Abstract Data Type provides the collection of operations supported by the set using a List Sequence.
Page 2
Selecting a Data Structure:
To implement the Set ADT, we must select a data structure. This is to be implemented either by using arrays
or by using list.
• An array could be used to implement the set, but a set can contain any number of elements and by
definition an array has a fixed size. To use the array structure, we would have to manage the expansion
of the array when necessary in the same fashion as it's done for the list.
• But the list can grow as needed, it seems ideal for storing the elements of a set and it does provide for
the complete functionality of the ADT. Even the list allows for duplicate values, we must make sure as
part of the implementation that no duplicates are added to our set.
Page 3
# Creates a new set from the union of this set and setB.
def union ( self, setB ) :
newSet = Set ()
newSet.s.extend ( self.s )
for element in setB.s :
if element not in self.s :
newSet.s.append ( element )
return newSet
# Creates a new set from the intersection: self set and setB.
def intersect ( self, setB ) :
newSet=Set()
for element in self.s:
if element in setB:
newSet.s.append(element)
return newSet
# Creates a new set from the difference: self set and setB.
def difference ( self, setB ) :
newSet=Set()
for element in self.s:
if element not in setB:
newSet.s.append(element)
return newSet
# Displays elements from set(or) iterator() method
def display( self ):
for ele in self.s:
print(ele,end="\t")
sobjA=Set()
sobjB=Set()
na=int(input("Enter no of elements to Set A="))
print("Enter SetA elements")
for i in range(na):
ele=int(input("Enter Element="))
sobjA.add(ele)
nb=int(input("Enter no of elements to Set B="))
print("Enter setB elements")
for i in range(nb):
ele=int(input("Enter Element="))
sobjB.add(ele)
print("Length of Set A=",len(sobjA))
print("Length of Set B=",len(sobjB))
print("Set A Elements")
sobjA.display()
print("\nSet B Elements")
sobjB.display()
#union
uni=sobjA.union(sobjB)
print("\nUnion of Set A and Set B")
uni.display()
#Intersection
Page 4
inter=sobjA.intersect(sobjB)
print("\nInterSection of Set A and Set B")
inter.display()
#Set Difference
dif=sobjA.difference(sobjB)
print("\nDifference of Set A and Set B")
dif.display()
print("\nRemove from SetA:")
e=int(input("Enter the element to remove="))
sobjA.remove(e)
print("After deletion operation SetA elements")
sobjA.display()
print("\n Contains in SetA ?")
e=int(input("Enter element to verify in setA="))
print("Element present in setA=",e in sobjA)
print("SetA equals to SetB?=",sobjA==sobjB)
print("SetA is Subset of SetB?=",sobjA.isSubsetOf(sobjB))
"""
Enter no of elements to Set A=5
Enter SetA elements
Enter Element=2
Enter Element=3
Enter Element=4
Enter Element=5
Enter Element=7
Enter no of elements to Set B=4
Enter setB elements
Enter Element=3
Enter Element=9
Enter Element=12
Enter Element=5
Length of Set A= 5
Length of Set B= 4
Set A Elements
2 3 4 5 7
Set B Elements
3 9 12 5
Union of Set A and Set B
2 3 4 5 7 9 12
InterSection of Set A and Set B
3 5
Difference of Set A and Set B
2 4 7
Remove from SetA:
Enter the element to remove=4
After deletion operation SetA elements
2 3 5 7
Contains in SetA ?
Enter element to verify in setA=5
Page 5
Element present in setA= True
SetA equals to SetB?= False
SetA is Subset of SetB?= False
"""
Maps:
• Searching for data items based on unique key values is a very common application in computer
science.
• An abstract data type that provides this type of search capability is often referred to as a map or
dictionary since it maps a key to a corresponding value.
• A Map or Dictionary is a data structure in which it stores values as a pair of key and value.
• A dictionary is a mutable, associative data structure of variable length.
Example Program:
student={'roll':777,'name':'venkat','branch':'CSE'}
print("Dictionary Accessing")
print("student['roll']:",student['roll'])
print("student['name']:",student['name'])
print("student['branch']:",student['branch'])
"""
Output
*******
Dictionary Accessing
student['roll']: 777
student['name']: venkat
student['branch']: CSE
"""
Page 6
Map Abstract Data Type:
A map is a container for storing a collection of data records in which each record is associated with a
unique key. The key components must be comparable.
1. Map(): Creates a new empty map.
2. length (): Returns the number of key/value pairs in the map.
3. contains ( key ): Determines if the given key is in the map and returns True if the key is found and
False otherwise.
4. add( key, value ): Adds a new key/value pair to the map if the key is not already in the map or
replaces the data associated with the key if the key is in the map. Returns True if this is a new key
and False if the data associated with the existing key is replaced.
5. remove( key ): Removes the key/value pair for the given key if it is in the map and raises an
exception otherwise.
6. valueOf ( key): Returns the data record associated with the given key. The key must exist in the map
or an exception is raised.
7. iterator (): Creates and returns an iterator that can be used to iterate over the keys in the map.
Page 7
Maps Implementation Using List:
class Map:
#Creation of a Map
def init ( self ):
self.entryList=list()
#Length of the Map
def len ( self ):
return len(self.entryList)
#Find the Position of the key
def findPosition( self,key ):
for i in range(len(self)):
if self.entryList[i].key==key:
return i
return None
#To check whether entry available or not
def contains ( self,key ):
pos=self.findPosition(key)
if pos is not None:
return True
else:
return False
#Add Entry to Map
def add( self,key,value ):
pos=self.findPosition(key)
if pos is not None:
self.entryList[pos].value=value
return False
else:
entry=MapEntry(key,value)
self.entryList.append(entry)
return True
#Remove Entry from Map
def remove( self,key ):
pos=self.findPosition(key)
assert pos is not None,"Invalid Map Entry"
self.entryList.pop(pos)
#Return Associated Value for key
Page 8
def valueOf( self,key ):
pos=self.findPosition(key)
assert pos is not None,"Invalid Map Entry"
return self.entryList[pos].value
#Display Elements from Map(or) Iterator
def display( self ):
for i in range(len(self)):
print("[",self.entryList[i].key,",",self.entryList[i].value,"]")
m=Map()
n=int(input("Enter no of entries to Map:"))
print("Enter Map Elements:")
for i in range(n):
print("Enter Element:",i)
k=int(input("Enter Key:"))
v=int(input("Enter Value:"))
m.add(k,v)
m.display()
print("Length of the Map",len(m))
print("Enter the key to check corresponding entry available or not:")
ck=int(input())
print(ck,"is available=?",ck in m )
print("Enter the key to remove corresponding map entry:")
rk=int(input())
m.remove(rk)
m.display()
print("Enter the key to find corrspoding Value:")
vk=int(input())
print(m.valueOf(vk))
"""
Enter no of entries to Map:5
Enter Map Elements:
Enter Element: 0
Enter Key:7
Enter Value:3
Enter Element: 1
Enter Key:77
Enter Value:33
Enter Element: 2
Enter Key:777
Enter Value:333
Page 9
En
te
r
El
em
en
t:
3
En
te
r
Ke
y:
77
77
En
te
r
Va
lu
e:
33
33
En
te
r
El
em
en
t:
4
En
te
r
Ke
y:
77
77
7
En
te
r
Va
lu
e:
33
33
3[
7
,
3
]
[ 77 , 33 ]
[ 777 , 333 ]
[ 7777 , 3333 ]
[ 77777 , 33333 ]
Length of the Map 5
Enter the key to check corresponding entry
available or not:777
777 is available=? True
Enter the key to remove corresponding map entry:
7777
[ 7 , 3 ]
[ 77 , 33 ]
[ 777 , 333 ]
[ 77777 , 33333 ]
Enter the key to find corrspoding Value:
777
3
3
3
"
"
"