Sets in Python:
=============
·     
A Set is an unordered collection data type that is iterable,
mutable, and has no duplicate elements. 
·     
Python’s set class represents the mathematical notion of a set.
·     
The major advantage of using a set, as opposed to a list, is
that it has a highly optimized method for checking whether a specific element
is contained in the set. 
·     
This is based on a data structure known as a hash table.
·     
However, the set itself is mutable. We can add or remove items
from it.
·     
To create a set, we use
the set() function.
How to create a set?
·      A set is created by placing
all the items (elements) inside curly braces {}, separated by comma or by using
the built-in function set().
·      It can have any number of
items and they may be of different types (integer, float, tuple, string etc.). 
·      But a set cannot have a
mutable element, like list, set or dictionary, as its element.
Examples:
# Set of integers
my_set = {1, 2, 3}
print(my_set)
# Set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# Set do not have
duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
# Set cannot have mutable
items
# here [3, 4] is a mutable list
# If you uncomment line #12,
# this will cause an error.
# TypeError: unhashable type: 'list'
#my_set = {1, 2, [3, 4]}
# We can make set from a
list
# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)
#Example of set
groceries = {'cereal','milk','starcrunch','beer','duct tape','lotion','beer'}
print(groceries)
if 'milk' in groceries:
print("You already have milk hoss!")
else:
print("Oh yes you need milk!")
groceries = {'cereal','milk','starcrunch','beer','duct tape','lotion','beer'}
print(groceries)
if 'milk' in groceries:
print("You already have milk hoss!")
else:
print("Oh yes you need milk!")
NOTE: Creating an empty set is a bit tricky.
Empty curly braces {} will
make an empty dictionary in Python. To make a set without any elements we use
the 
set() function without
any argument.
#
initialize a with {}
a = {}
# check
data type of a
# Output: <class 'dict'>
print(type(a))
#
initialize a with set()
a = set()
# check
data type of a
# Output: <class 'set'>
print(type(a))
Frozen Sets
Frozen sets are immutable objects that only
support methods and operators that produce a result without affecting the
frozen set or sets to which they are applied.
# Python program to demonstrate differences
# between normal and frozen set
# Same as {"a",
"b","c"}
normal_set = set(["a",
"b","c"])
# Adding an element to normal set is fine
normal_set.add("d")
print("Normal Set")
print(normal_set)
# A frozen set
frozen_set = frozenset(["e",
"f", "g"])
print("Frozen Set")
print(frozen_set)
# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")
Output:
======
Normal Set
set(['a', 'c', 'b', 'd'])
Frozen Set
frozenset(['e', 'g', 'f'])
Methods for Sets:
==============
1. add(x) Method: Adds the item x to set if
it is not already present in the set.
people = {"Jay", "Idrish",
"Archil"}
people.add("Daxit") 
-> This
will add Daxit in people set.
2. union(s) Method: Returns a
union of two set.Using the ‘|’ operator between 2 sets is the same as writing
set1.union(set2)
people
= {"Jay", "Idrish", "Archil"}
vampires
= {"Karan", "Arjun"}
population
= people.union(vampires)
ALITER
population = people|vampires
->
Set population set will have components of both people and vampire
3. intersect(s) Method: Returns an intersection
of two sets.The ‘&’ operator comes can also be used in this case.
victims = people.intersection(vampires)
-> Set
victims will contain the common element of people and vampire
4. difference(s) Method: Returns a set containing all the
elements of invoking set but not of the second set. We can use ‘-‘
operator here.
safe
= people.difference(vampires)
ALITER
safe
= people – vampires
-> Set
safe  will have all the elements that are in people but not vampire
5. clear() Method: Empties the whole set.
victims.clear()
-> Clears victim set
However there are two
major pitfalls in Python sets:
1.  
The
set doesn’t maintain elements in any particular order.
2.  
Only
instances of immutable types can be added to a Python set.
Operators for Sets
Sets and frozen sets
support the following operators:
key in s           # containment check
key not in s    # non-containment check
s1 == s2         # s1 is equivalent to s2
s1 != s2         # s1 is not equivalent to
s2
s1 <= s2        # s1is subset of s2
s1 < s2         # s1 is proper subset of
s2
s1 >= s2      # s1is superset of s2
s1 > s2        # s1 is proper superset
of s2
s1 | s2         # the union of s1 and s2
s1 & s2      # the intersection of s1 and s2
s1 – s2       # the set of elements in s1 but not s2
s1 ˆ s2       # the set of elements in precisely one of s1 or s2
Code Snippet to illustrate all Set operations in Python
# Python program to
  demonstrate working# of 
# Set in Python 
# Creating two sets 
set1
  = set() 
set2
  = set() 
# Adding elements to
  set1 
for i
  in range(1, 6): 
    set1.add(i) 
# Adding elements to
  set2 
for i
  in range(3, 8): 
    set2.add(i) 
print("Set1
  = ", set1) 
print("Set2
  = ", set2) 
print("\n") 
# Union of set1 and
  set2 
set3
  = set1 | set2# set1.union(set2) 
print("Union
  of Set1 & Set2: Set3 = ", set3) 
# Intersection of
  set1 and set2 
set4
  = set1 & set2#
  set1.intersection(set2) 
print("Intersection
  of Set1 & Set2: Set4 = ", set4) 
print("\n") 
# Checking relation
  between set3 and set4 
if set3
  > set4: # set3.issuperset(set4) 
    print("Set3
  is superset of Set4") 
elif set3
  < set4: # set3.issubset(set4) 
    print("Set3
  is subset of Set4") 
else :
  # set3 == set4 
    print("Set3
  is same as Set4") 
# displaying
  relation between set4 and set3 
if set4
  < set3: # set4.issubset(set3) 
    print("Set4
  is subset of Set3") 
    print("\n") 
# difference between
  set3 and set4 
set5
  = set3 -
  set4 
print("Elements
  in Set3 and not in Set4: Set5 = ", set5) 
print("\n") 
# checkv if set4 and
  set5 are disjoint sets 
if set4.isdisjoint(set5): 
    print("Set4
  and Set5 have nothing in common\n") 
# Removing all the
  values of set5 
set5.clear() 
print("After
  applying clear on sets Set5: ") 
print("Set5
  = ", set5) 
Output: 
('Set1 = ', set([1, 2, 3, 4, 5])) 
('Set2 = ', set([3, 4, 5, 6, 7])) 
('Union of Set1 & Set2: Set3 =
  ', set([1, 2, 3, 4, 5, 6, 7])) 
('Intersection of Set1 & Set2:
  Set4 = ', set([3, 4, 5])) 
Set3 is superset of Set4 
Set4 is subset of Set3 
('Elements in Set3 and not in
  Set4: Set5 = ', set([1, 2, 6, 7])) 
Set4 and Set5 have nothing in
  common 
After applying clear on sets Set5:
   
('Set5 = ', set([])) 
 | 
 
Basic Types in Python in a Line
========================
a=10 #int
b="hello" #str
c=2.5 #float
e=bytearray() #bytearray
f=(1,2,3) #tuple
g=[1,2,3] #list
h={1,2,3} #set
i={} #dict
j=b"sample" #bytes
k=None #empty
=========================
a=10 #int
b="hello" #str
c=2.5 #float
e=bytearray() #bytearray
f=(1,2,3) #tuple
g=[1,2,3] #list
h={1,2,3} #set
i={} #dict
j=b"sample" #bytes
k=None #empty
=========================
Question : What is the
difference between a set and a dictionary?
A set is an unordered data type which has no duplicate items
inside it. a dictionary arranges items as {"key": "value"}
pairs. sets are very handy when comparisons are to be made since sets handle
data in a very controlled way as they dont allow duplicates, but dicts are
useful when we want to store a bunch a data inside a single key, for example,
all the cources offered in a school could be values stored inside the key which
could be the school name, this is useful if we were handling large amount data
that involved working with all the schools of a region.
Sets Related Programs:
===================
1. Program to Count the Number of Vowels
Present in a String using Sets:
s=input("Enter
string:")
count
= 0
vowels
= set("aeiou")
for
letter in s:
    if letter in vowels:
        count += 1
print("Count
of the vowels is:")
print(count)
Output:
======
1:
Enter
string:Hello world
Count
of the vowels is:
3
2:
Enter
string: manish
Count
of the vowels is:
2
2. Program to Check Common Letters in Two Input
Strings.
s1=input("Enter
first string:")
s2=input("Enter
second string:")
a=list(set(s1)&set(s2))
print("The
common letters are:")
for
i in a:
    print(i)
Output:
======
1:
Enter
first string: manish
Enter
second string: bidsar
The
common letters are:
a
i
s
2:
Enter
first string:Test string
Enter
second string:checking
The
common letters are:
i
e
g
n
3.  Program that displays which Letters
are in the First String but not in the Second
s1=input("Enter
first string:")
s2=input("Enter
second string:")
a=list(set(s1)-set(s2))
print("The
letters are:")
for
i in a:
    print(i)
Output:
======
1:
Enter
first string: manish
Enter
second string: bidsar
The
letters are:
n
h
m
2:
Enter
first string:Python
Enter
second string:Programming language
The
letters are:
y
h
t
4.  Program that Displays which Letters
are Present in Both the Strings
s1=input("Enter
first string:")
s2=input("Enter
second string:")
a=list(set(s1)|set(s2))
print("The
letters are:")
for
i in a:
    print(i)
Output:
======
1:
Enter
first string:hello
Enter
second string:world
The
letters are:
e
d
h
l
o
r
w
2:
Enter
first string:test
Enter
second string:string
The
letters are:
e
g
i
n
s
r
t
5. Program
that Displays which Letters are in the Two Strings but not in Both
s1=input("Enter
first string:")
s2=input("Enter
second string:")
a=list(set(s1)^set(s2))
print("The
letters are:")
for
i in a:
    print(i)
Output:
======
1:
Enter
first string: manish
Enter
second string: bidsar
The
letters are:
n
b
m
d
h
r
2:
Enter
first string:hello
Enter
second string:world
The
letters are:
e
d
h
r
w
For a Quick Recap Watch the Below Video :
For a Quick Recap Watch the Below Video :
No comments:
Post a Comment
Note: only a member of this blog may post a comment.