0% found this document useful (0 votes)
3 views

SETS AND MAPS

The document provides an overview of sets and maps as abstract data types in Python. It explains the properties and operations of sets, including creation, modification, and mathematical operations, along with their implementation using lists. Additionally, it covers maps (dictionaries), detailing their structure, operations, and implementation, including examples of usage in Python code.

Uploaded by

Tejas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

SETS AND MAPS

The document provides an overview of sets and maps as abstract data types in Python. It explains the properties and operations of sets, including creation, modification, and mathematical operations, along with their implementation using lists. Additionally, it covers maps (dictionaries), detailing their structure, operations, and implementation, including examples of usage in Python code.

Uploaded by

Tejas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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=set (['cse','ece','eee','me','ce'])

>>> s1

{'me', 'ece', 'ce', 'cse', 'eee'}

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.

Abstract Data Type Set


A set is a container that stores a collection of unique values over a given comparable domain in which
the stored values have no particular ordering.
Set() Creates a new set initialized to the empty set.
length () Returns the number of elements in the set, also known as the cardinality.
Accessed using the len() function.
contains ( element ) Determines if the given value is an element of the set and returns the
appropriate boolean value. Accessed using the in operator.
add( element ) Modifies the set by adding the given value or element to the set if the element is
not already a member. If the element is not unique, no action is taken and the
operation is skipped.
remove( element ) Removes the given value from the set if the value is contained in the set and
raises an exception otherwise.
equals ( setB ) Determines if the set is equal to another set and returns a boolean value. For two
sets, A and B, to be equal, both A and B must contain the same number of elements
and all elements in A must also be elements in B. If both sets are
empty, the sets are equal. Access with == or !=.
isSubsetOf( setB ) Determines if the set is a subset of another set and returns a boolean value. For
set A to be a subset of B, all elements in A must also be elements in B.
union( setB ) Creates and returns a new set that is the union of this set and setB. The new set
created from the union of two sets, A and B, contains all elements in A plus those
elements in B that are not in A. Neither set A nor set B is modified by this
operation.
intersect( setB ) Creates and returns a new set that is the intersection of this set and setB. The
intersection of sets A and B contains only those elements that are in both A and
B. Neither set A nor set B is modified by this operation.
difference( setB ) Creates and returns a new set that is the difference of this set and setB. The set
difference, A-B, contains only those elements that are in A but not in B. Neither
set A nor set B is modified by this operation.
iterator () Creates and returns an iterator that can be used to iterate over the collection of
items.

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.

So the sets are implemented by List data structure.

Sets implementation Using Python List:

#Set ADT implementation


class Set:
# Creates an empty set
def init ( self ) :
self.s= list()
# Returns the number of items in the set.
def len ( self ) :
return len ( self.s)
# Determines if an element is in the set.
def contains ( self, element ) :
#print("From Contains function")
return element in self.s
# Adds a new unique element to the set.
def add ( self, element ) :
if element not in self.s :
self.s.append ( element )
# Removes an element from the set.
def remove ( self, element ) :
assert element in self.s, "The element must be in the set."
self.s.remove ( element )
# Determines if two sets are equal.
def eq ( self, setB ) :
if len ( self ) != len ( setB ) :
return False
else :
return self.isSubsetOf ( setB )
# Determines if this set is a subset of setB.
def isSubsetOf ( self, setB ) :
for element in self.s :
if element not in setB :
return False
return True

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.

Syntax for defining Dictionary in Python:


dic_name= {key1:value1, key2: value, key3:valu3,……, keyn: valuen},
Declaring Empty Dictionary:
dic_name= { }
Example for Dictionary:
dic= {‘Roll_Number’:’19701A0599’,’Name’:’Rajesh’,’Branch’:’CSE’}
Accessing Elements from Dictionary:
value=dic_name[key]

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.

Map implementation using List:


• In the implementation of the Set ADT, we used a single list to store the individual elements. For the
Map ADT, however, we must store both a key component and the corresponding value component for
each entry in the map.
• We cannot simply add the component pairs to the list without some means of maintaining their
association.
• The individual keys and corresponding values can both be saved in a single object, with that object then
stored in the list. A sample instance illustrating the data organization required for this approach is shown
in Figure.

Page 7
Maps Implementation Using List:

#Implementation for MAP ADT


class MapEntry:
def init ( self,key,value ):
self.key=key
self.value=value

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
"
"
"

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy