Lab 3-AI
Lab 3-AI
Sciences
Lab Manual 03
AL2002-Artificial Intelligence
Lab
Table of Contents
Task Distribution..........................................................................................................................................2
Lecture........................................................................................................................................................2
Exercise (20 marks)......................................................................................................................................8
Task Distribution
Total Time 160 Minutes
Demo 15 Minutes
Exercise 130 Minutes
Submission 15 Minutes
Lecture
• 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
dataScientist | dataEngineer
# Intersection operation
dataScientist.intersection(dataEngineer)
# Equivalent Result
dataScientist & dataEngineer
# Difference Operation
dataScientist.difference(dataEngineer)
# Equivalent Result
dataScientist – dataEngineer
# Equivalent Result
dataScientist ^ dataEngineer
• 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.
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.
• Types of Exceptions
Here’s a list of the common exceptions you’ll come across in Python:
• ImportError: It is raised when you try to import the library that is not installed or you
have provided the wrong name
• 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
• IndentationError: Raised when indentation is not specified properly
• ZeroDivisionError: It is raised when you try to divide a number by zero
• ValueError: Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified
• 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 raises 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.
Output:
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.")
Output:
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}")
Output:
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 the 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:
print(f"Cannot sum the variables. The exception was
{e}")
Output:
Cannot sum the variables. The exception was name 'a' is not
defined
• 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..except and finally
"finally" and "except" can be used together for the same try block, as it can be seen in the
following Python example:
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.")
}
keysToRemove = ["name", "salary"]
Output:
{'city': 'New york', 'age': 25}