AI Lab Manual 4
AI Lab Manual 4
Lab Manual 04
CL461-Artificial Intelligence Lab
Section E
Semester Spring 2023
Table of Contents
1 Objectives ............................................................................................................................... 3
2 Task Distribution ..................................................................................................................... 3
3 Python Sets.............................................................................................................................. 3
3.1 Set Initialization Examples............................................................................................... 3
3.2 Set Modification Examples .............................................................................................. 4
3.3 Set Operations .................................................................................................................. 4
3.4 Frozensets ......................................................................................................................... 5
4 Python Exception Handling .................................................................................................... 6
4.1 Types of Exceptions ......................................................................................................... 6
4.2 Exception Handling with Try Except Clause ................................................................... 6
4.3 Re-raise the exception ...................................................................................................... 7
4.4 Catch certain types of exception ...................................................................................... 7
4.5 Try….Finally .................................................................................................................... 8
4.6 Try..except and finally ...................................................................................................... 8
5 Python File Handling .............................................................................................................. 9
5.1 Open & Close a file .......................................................................................................... 9
5.2 Kinds of modes................................................................................................................. 9
5.3 Working of read() mode ................................................................................................... 9
5.4 Working of write() mode ................................................................................................ 10
5.5 Working of append() mode............................................................................................. 10
6 Python Iterators ..................................................................................................................... 10
6.1 Building Custom Iterators ...............................................................................................11
7 Exercise (25 marks) ...............................................................................................................11
7.1 Set Operations (5 marks) .................................................................................................11
7.2 Exception Handling for Division (5 marks) ................................................................... 12
7.3 Reading text from a file and storing it in reversed order (10 marks) ............................. 12
8 Submission Instructions ........................................................................................................ 12
CL461: Artificial Intelligence Lab
1 Objectives
After performing this lab, students shall be able to understand Python data structures which
include:
✓ Python sets
✓ Python exception handling
✓ Python file handling
✓ Python iterators
2 Task Distribution
Total Time 170 Minutes
Exercise 90 Minutes
3 Python Sets
Sets have following characteristics:
• Set in Python is a data structure equivalent to sets in mathematics.
• Sets are a mutable collection of distinct (unique) immutable values that are unordered.
• Any immutable data type can be an element of a set: a number, a string, a tuple.
• Mutable (changeable) data types cannot be elements of the set.
• In particular, list cannot be an element of a set (but tuple can), and another set cannot be
an element of a set.
• You can perform standard operations on sets (union, intersection, difference).
# Initialize sets
dataScientist = set(['Python', 'R', 'SQL', 'Git', 'Tableau', 'SAS'])
dataEngineer = set(['Python', 'Java', 'Scala', 'Git', 'SQL', 'Hadoop']
)
# Equivalent Result
CL461: Artificial Intelligence Lab
dataScientist | dataEngineer
# Intersection operation
dataScientist.intersection(dataEngineer)
# Equivalent Result
dataScientist & dataEngineer
# Difference Operation
dataScientist.difference(dataEngineer)
# Equivalent Result
dataScientist – dataEngineer
# Equivalent Result
dataScientist ^ dataEngineer
3.4 Frozensets
You have encountered nested lists and tuples. The problem with nested sets is that you cannot
normally have nested sets as sets cannot contain mutable values including sets.
• A frozenset is very similar to a set except that a frozenset is immutable.
• The primary reason to use them is to write clearer, functional code.
• By defining a variable as a frozen set, you’re telling future readers: do not modify this.
• If you want to use a frozen set you’ll have to use the function to construct it. No other
way.
# Initialize a frozenset
immutableSet = frozenset()
# Initialize a frozenset
nestedSets = set([frozenset()])
A major disadvantage of a frozenset is that since they are immutable, it means that you cannot
add or remove values.
CL461: Artificial Intelligence Lab
ZeroDivisionError and TypeError are the error type and the text that comes after the colon is the
error message. The error message usually describes the error type.
1. ImportError: It is raised when you try to import the library that is not installed or you
have provided the wrong name
2. IndexError: Raised when an index is not found in a sequence. For example, if the length
of the list is 10 and you are trying to access the 11th index from that list, then you will get
this error
3. IndentationError: Raised when indentation is not specified properly
4. ZeroDivisionError: It is raised when you try to divide a number by zero
5. ValueError: Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified
6. Exception: Base class for all exceptions. If you are not sure about which exception may
occur, you can use the base class. It will handle all of them
try:
// some code
except:
// what to do when the code in try raise an exception
In plain English, the try except clause is basically saying, “Try to do this, except (otherwise) if
there’s an error, then do this instead”.
There are a few options on what to do with the thrown exception from the try block. Let’s
discuss them.
CL461: Artificial Intelligence Lab
try:
myfunction(100, "one hundred")
except:
raiseTraceback (most recent call last):
File "<input>", line 2, in <module>
File "<input>", line 2, in myfunction
TypeError: unsupported operand type(s) for +: 'int' and 'str'
try:
myfunction(100, "one hundred")
except TypeError:
print("Cannot sum the variables. Please pass numbers
only.")Cannot sum the variables. Please pass numbers only.
To make it even better, we can actually log or print the exception itself.
try:
myfunction(100, "one hundred")
except TypeError as e:
print(f"Cannot sum the variables. The exception was:
{e}")Cannot sum the variables. The exception was: unsupported
operand type(s) for +: 'int' and 'str'
Furthermore, we can catch multiple exception types in one except clause if we want to handle
those exception types the same way. Let’s pass an undefined variable to our function so that it
will raise the NameError. We will also modify our except block to catch
both TypeError and NameError and process either exception type the same way.
try:
myfunction(100, a)
except (TypeError, NameError) as e:
CL461: Artificial Intelligence Lab
4.5 Try….Finally
So far the try statement had always been paired with except clauses. But there is another way to
use it as well. The try statement can be followed by a finally clause. Finally clauses are called
clean-up or termination clauses, because they must be executed under all circumstances, i.e. a
"finally" clause is always executed regardless if an exception occurred in a try block or not. A
simple example to demonstrate the finally clause:
try:
x = float(input("Your number: "))
inverse = 1.0 / x
finally:
print("There may or may not have been an exception.")
print("The inverse: ", inverse)
Your number: 34
There may or may not have been an exception.
The inverse: 0.029411764705882353
try:
x = float(input("Your number: "))
inverse = 1.0 / x
except ValueError:
print("You should have given either an int or a float")
except ZeroDivisionError:
print("Infinity")
finally:
print("There may or may not have been an exception.")
Your number: 23
There may or may not have been an exception.
CL461: Artificial Intelligence Lab
open(filename, mode)
5.2 Kinds of modes
There are three basic types of modes in which files can be opened in Python.
mode meaning
r+ open for both reading and writing (file pointer is at the beginning of the file)
w+ open for both reading and writing (truncate the file if it exists)
open for writing (append to the end of the file if exists & file pointer is at the end of the
a
file)
Always keep in mind that the mode argument is not mandatory. If not passed, then Python will
assume it to be “ r ” by default.
Let’s look at this program and try to analyze how the read mode works:
Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first five characters of stored data and return it as a string:
# Python code to illustrate read() mode character wise
file = open("file.txt", "r")
print (file.read(5))
The close() command terminates all the resources in use and frees the system of this particular
program.
6 Python Iterators
An iterator is an object that contains a countable number of values. It is an object that can be
iterated upon, meaning that you can traverse through all the values. Technically, in Python, an
iterator is an object which implements the iterator protocol, which consist of the
methods __iter__() and __next__().
Every time you ask an iterator for the next item, it calls its __next__method. If there is
another value available, the iterator returns it. If not, it raises a StopIteration exception.
More information about iterators can be found here.
This behavior (only returning the next element when asked to) has two main advantages:
1. Iterators need less space in memory. They remember the last value and a rule to get to
the next value instead of memorizing every single element of a (potentially very long)
sequence.
CL461: Artificial Intelligence Lab
2. Iterators don’t check how long the sequence they produce might get. For instance, they
don’t need to know how many lines a file has or how many files are in a folder to iterate
through them.
(One important note: don’t confuse iterators with iterables. Iterables are objects that can create
iterators by using their __iter__ method)
The __next__() method must return the next item in the sequence.
print(next(myit))
print(next(myit))
print(next(myit))
mystr = "banana"
for x in mystr:
print(x)
The for loop actually creates an iterator object and executes the next() method for each loop.
7.3 Reading text from a file and storing it in reversed order (10 marks)
Design a code which reads text from the file “Alphabets.txt” and stores its data in reverse order
in another file. For this you may upload the given text file on Google Collab’s session and define
the path as:
file_path= ‘/Alphabets.txt’
The same convention can be followed for defining path of the resultant file (reversed text file)
For more information read this.
8 Submission Instructions
Always read the submission instructions carefully.
• Rename your Jupyter notebook to your roll number and download the notebook as .ipynb
extension.
• To download the required file, go to File->Download .ipynb
• Only submit the .ipynb file. DO NOT zip or rar your submission file
• Submit this file on Google Classroom under the relevant assignment.
• Late submissions will not be accepted