AIML__MODULE__1
AIML__MODULE__1
Description:
The print() function is used to display output on the console. It can take multiple arguments to print, separated
by a default space, and allows customization of separators (sep), line endings (end), and output destinations
(file).
Code:
print("Hello, World!")
Output:
Hello, World!
Input :-
Syntax:
variable = input(prompt)
Description:
The input() function is used to take user input as a string. The optional prompt displays a message to the user
before input is provided.
Code:
name = input("Enter your name: ")
print(f"Hello, {name}!")
Output:
Enter your name: John
Hello, John!
3. Conditional Statements
If else :-
Syntax:
if condition:
else:
Description:
The if-else statement is used for decision-making in Python. It executes one block of code if the condition is
True and another block if the condition is False.
Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
Output:
Enter a number: 5
5 is odd.
4. Loops
While:-
Syntax:
while condition:
Description:
The while loop is used to repeatedly execute a block of code as long as the given condition
evaluates to True. It is commonly used for indefinite iteration when the number of iterations
is not known in advance.
While Loop:
i=1
while i <= 5:
print(i)
i += 1
Output:
1
For:-
Syntax:
Description:
The for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable. It executes
the block of code once for each item in the sequence.
For Loop:
for i in range(1, 6):
print(i)
Output:
1
5. Functions
Def :-
Syntax:
def function_name(parameters):
# Code block defining the function
Description:
The def keyword is used to define a function in Python. A function is a reusable block of code that performs a
specific task. It can accept parameters, perform operations, and optionally return a value.
Code:
def add(x, y):
return x + y
Output:
Enter the first number: 7
6. List Operations
List:-
Syntax:
Description:
A list is a mutable, ordered collection in Python that can store elements of any data type. Items in a list can be
added, removed, or modified. Lists are defined using square brackets [].
Code:
# Demonstrating List Operations
print("\nList Operations")
my_list = [1, 2, 3, 4, 5]
# Adding elements
my_list.append(6)
my_list.insert(2, 10)
# Removing elements
my_list.remove(10)
popped_element = my_list.pop()
# Other operations
my_list.reverse()
my_list.sort()
Output:
List Operations
Element at index 1: 2
Length of List: 5
7. Dictionary Example
Dictionary:-
Syntax:
Description:
A dictionary is an unordered, mutable collection in Python that stores data as key-value pairs. Keys must be
unique and immutable, while values can be of any data type. Dictionaries are defined using curly braces {}.
Code:
# Demonstrating Dictionary Operations
print("\nDictionary Operations")
# Accessing elements
print("Name:", my_dict["name"])
print("Keys:", my_dict.keys())
print("Values:", my_dict.values())
my_dict["country"] = "USA"
my_dict["age"] = 26
# Removing elements
deleted_value = my_dict.pop("city")
# Other operations
print("Items:", my_dict.items())
my_dict.clear()
Output:
Dictionary Operations
Name: Alice
After adding country: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
After updating age: {'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}
After pop (city): New York Dictionary: {'name': 'Alice', 'age': 26, 'country': 'USA'}
After clear: {}
8. Tuple Example
Tuple:-
Syntax:
Description:
A tuple is an immutable, ordered collection in Python that can store elements of any data type. Once defined,
the items in a tuple cannot be changed. Tuples are defined using parentheses ().
Code:
# Demonstrating Tuple Operations
print("\nTuple Operations")
# Accessing elements
# Other operations
print("Length of Tuple:", len(my_tuple))
Output:
Tuple Operations
Element at index 2: 30
Length of Tuple: 5
Count of 20 in Tuple: 1
Index of 30 in Tuple: 2
9. Set Example
Set:-
Syntax:
Description:
A set is an unordered, mutable collection in Python that does not allow duplicate elements. Sets are typically
used to store unique items and are defined using curly braces {}.
Code:
# Demonstrating Set Operations
print("\nSet Operations")
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
my_set.remove(3)
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print("Union:", set1.union(set2))
print("Intersection:", set1.intersection(set2))
print("Difference:", set1.difference(set2))
Output:
Set Operations
Union: {1, 2, 3, 4, 5}
Intersection: {3}
Difference: {1, 2}
10. PLOT Y = X
Numpy :-
Syntax:
import numpy as np
Description:
NumPy is a powerful library for numerical computing in Python. It provides support for large, multi-
dimensional arrays and matrices, along with a collection of mathematical functions to operate on them
efficiently. The common alias np is used for convenience.
Code:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10)
y=x
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of y = x')
plt.grid(True)
plt.show()
Output:
Description:
Matplotlib is a plotting library for Python that provides a variety of tools to create static, animated, and
interactive visualizations. pyplot is a commonly used module within matplotlib for creating plots and charts,
and it's typically imported as plt.
Code:
import numpy as np
dx = 0.01
x = np.arange(0, 2 * np.pi, dx)
y = np.sin(x)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Plot of y = sin(x)')
plt.legend()
plt.grid(True)
plt.show()
Output:
12.PIE CHAT
Pie:-
Syntax:
Description:
The pie() function in matplotlib creates a pie chart. It takes a list of sizes representing the portions of each pie
slice, and labels to name each slice. Optional parameters like autopct display the percentage on each slice, and
startangle rotates the chart for better visualization.
Code:
import matplotlib.pyplot as plt
plt.legend()
plt.show()
Output:
13. BARGRAPH
Bar:-
Syntax:
The bar() function in matplotlib creates a bar chart. It takes the x positions of the bars and their corresponding
height values. Optional parameters like width control the thickness of the bars, and align determines how the
bars are aligned along the x-axis.
Code:
import matplotlib.pyplot as plt
values = [5, 7, 3, 8]
plt.xlabel('Categories')
plt.ylabel('Values')
plt.legend()
plt.show()
Output:
2.Algorithm for Breadth First Search (BFS)
ALGORITHM:-
1. Initialize a queue and mark the starting node as visited.
FLOWCHART:-
DESCRIPTION :-
deque in module collections :-
class deque(builtins.object)
dict object :-
class dict(object)
d = {}
class set(object)
add( ) :-
append( ) :-
PROGRAM 1:-
from collections import deque
graph = {
'A': ['B', 'C'],
'D': ['B'],
start = 'A'
# Perform BFS
while queue:
OUTPUT :-
ABCDEF
PROGRAM 2:-
from collections import deque
graph = {
'A': ['B', 'C','D'],
'B': [ 'E','F'],
'C': ['G','H'],
'D': ['I'],
'E': ['J','K'],
'F': [],
'G': ['L'],
'H': [],
'I': ['M'],
'J': [],
'K': ['N'],
'L': [],
'M': [],
'N': []
start = 'A'
# Perform BFS
while queue:
PROGRAM 3:-
from collections import deque
graph = {
'B': [ 'E','F'],
'C': ['G','H'],
'D': ['I'],
'E': ['J','K'],
'F': [],
'G': ['L'],
'H': [],
'I': ['M'],
'J': [],
'K': ['N'],
'L': [],
'M': [],
'N': []
start = 'A'
GOAL='G'
# Perform BFS
while queue:
break
Output :-
ABCDEFG
PROGRAM 4 :-
from collections import deque
def input_graph():
graph = {}
for _ in range(num_nodes):
graph[node] = neighbors
return graph
graph = input_graph()
# Perform BFS
found = False
while queue:
found = True
break
if not found:
OUTPUT :-
Enter the number of nodes in the graph: 5
ABCDE
_____________________________________________
3.Algorithm for Depth First Search (DFS)
ALGORITHM:-
DESCRIPTION :-
reversed :-
class reversed(
sequence: Reversible[_T@reversed],
/
)
dict object(graph) :-
class dict(object)
dict() -> new empty dictionary
d = {}
class set(object)
add( ) :-
append( ) :-
Pop( ) :-
'C': ['G'],
'D': [],
'E': [],
'F': [],
'G': []
# Initialize
start_node = 'A'
while stack:
stack.append(neighbor)
Output :-
DFS Traversal Order:
ABEFCGD
PROGRAM 2:-
graph = {
'B': [ 'E','F'],
'C': ['G','H'],
'D': ['I'],
'E': ['J','K'],
'F': [],
'G': ['L'],
'H': [],
'I': ['M'],
'J': [],
'K': ['N'],
'L': [],
'M': [],
'N': []
# Initialize
start_node = 'A'
while stack:
stack.append(neighbor)
OUTPUT :-
DFS Traversal Order:
ABEJKNFCGLHDIM
PROGRAM 3:-
# Graph represented as an adjacency list
graph = {
'C': ['G'],
'D': [],
'E': [],
'F': [],
'G': []
# Initialize
start_node = 'A'
goal='E'
while stack:
stack.append(neighbor)
OUTPUT :-
DFS Traversal Order:
ABE
PROGRAM 4 :-
def get_graph():
graph = {}
print("Enter the adjacency list of the graph (format: node: neighbor1 neighbor2 ...). Enter 'done' to finish:")
while True:
line = input().strip()
if line.lower() == 'done':
break
parts = line.split(":")
if len(parts) != 2:
print("Invalid format. Please use the format: node: neighbor1 neighbor2 ...")
continue
node = parts[0].strip()
neighbors = parts[1].split()
graph[node] = neighbors
return graph
def get_start_and_goal():
graph = get_graph()
visited = set()
stack = [start_node]
while stack:
current_node = stack.pop()
visited.add(current_node)
if current_node == goal_node:
break
stack.append(neighbor)
else:
OUTPUT :-
Depth First Search (DFS)
Enter the adjacency list of the graph (format: node: neighbor1 neighbor2 ...). Enter 'done' to finish:
A:B C
B:D E
C:F G
D:
E:
F:
G:
DONE
ABDECFG
___________________________________________________________________________
Dequeue the node current with the lowest heuristic value from pq.
FLOWCHART:-
priority queue:-
Syntax:
import queue
pq = queue.PriorityQueue()
import heapq
pq = []
Description:
A priority queue is a data structure where elements are dequeued based on their priority instead of their
insertion order. Lower numerical values indicate higher priority by default. The queue.PriorityQueue class
provides a thread-safe implementation, while heapq provides a lightweight heap-based alternative.
Continue:-
Syntax:
for i in range(5):
if i == 2:
continue # Skip the rest of the loop body for this iteration
print(i)
Description:
The continue statement is used inside loops to skip the current iteration and move to the next iteration
immediately, without executing the remaining code in the loop body.
PROGRAM :-
import heapq
0: [1, 2],
1: [0, 3, 4],
2: [0, 5],
3: [1],
4: [1],
5: [2]
heuristic = {
0: 10,
1: 8,
2: 5,
3: 7,
4: 3,
# Initialization
start_node = 0
goal_node = 5
priority_queue = []
visited = set()
path = []
# Best-First Search
while priority_queue:
_, current = heapq.heappop(priority_queue)
if current in visited:
continue
visited.add(current)
path.append(current)
if current == goal_node:
break
OUTPUT :-
__________________________________________________________________________________________
5.Algorithm for A* Search
Inputs:
1. Graph: A tree with nodes and edges where each edge has a cost.
4. Heuristic: A heuristic function or pre-defined values estimating the cost from each node to the goal
node.
Outputs:
The optimal path from the start node to the goal node, or a message saying no path exists.
ALGORITHM:-
1. Initialization:
o Define the open list: A priority queue (min-heap) which will hold nodes that need to be
evaluated.
o Define the closed list: A set to keep track of nodes that have already been evaluated.
o Define Actual cost(g-cost) for each node, which represents the cost from the start node to
the current node.
o Define heuristic values(h value) for each node, which estimate the cost from that node to the
goal node.
2. Start:
o Add the start node to the open list with its F Value.
3. Main Loop:
1. Select the node from the open list that has the lowest F Value. This node is the most
promising candidate for exploration.
2. If this node is the goal node, the search is complete. Reconstruct the path from the
goal node back to the start node.
3. Otherwise, move the current node from the open list to the closed list, marking it as
explored.
For each neighbor, calculate the tentative g-cost: the cost to reach that
neighbor through the current node.
If the neighbor has not been evaluated (i.e., it’s not in the closed list), or if a
better path to that neighbor is found (i.e., the tentative g-value is lower
than the current g-value), then:
Update the g-value for that neighbor.
4. Termination:
o If the open list becomes empty and no path to the goal node is found, return that no path
exists.
FLOWCHART:-
heap-based priority queue:-
Syntax:
import heapq
# Creating a min-heap
heap = []
heapq.heappush(heap, 3)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
smallest = heapq.heappop(heap)
Description:
The heapq module provides a heap-based priority queue in Python. It implements a min-heap by default, where
the smallest element is always at the root. It allows efficient insertion and removal of the smallest element in
O(log n) time.
PROGRAM :-
import heapq
nodes = {
"A": {"B": 1, "C": 4}, # A has children B and C, costs 1 and 4 respectively
"B": {"D": 2, "E": 5}, # B has children D and E, costs 2 and 5 respectively
}
# Heuristic values (estimated cost to reach the goal)
heuristic = {
"B": 5,
"C": 2,
"D": 1,
"E": 1,
open_list = []
closed_list = set()
while open_list:
if current_node == goal:
path = []
path.append(current_node)
current_node = came_from[current_node]
path.append(start)
path.reverse()
print("Path found:", path)
break
closed_list.add(current_node)
# Explore neighbors
if neighbor in closed_list:
continue
g_score[neighbor] = tentative_g_score
came_from[neighbor] = current_node
else:
OUTPUT :-
Path found: ['A', 'B', 'D', 'G']
___________________________________________________________________________
6.Constraint Satisfaction Problem ( CSP )
3. Constraints – The rules or conditions that restrict the values the variables can take.
CSPs are commonly used in scheduling, planning, optimization, and artificial intelligence
applications such as Sudoku, map coloring, and the N-Queens problem. Popular solving
techniques include backtracking, constraint propagation, and heuristic search algorithms
like AC-3 and Min-Conflicts.
Create a list colors of size VVV initialized with -1 to represent uncolored vertices.
Check if assigning a specific color to a vertex is valid by ensuring no adjacent vertex has the same
color.
o If assigning a color leads to a dead end, backtrack by removing the assigned color and trying
the next one.
PROGRAM :-
# Define the number of vertices in the graph
V=4
graph = [
# Number of colors
# Check all adjacent vertices to ensure no adjacent vertex has the same color
for i in range(V):
return False
return True
return True
return True
colors[vertex] = -1
print("Solution found:")
else:
OUTPUT :-
Solution found:
Mean-End Analysis (MEA) is a problem-solving technique used in artificial intelligence and cognitive
psychology. It is a heuristic method that breaks down a complex problem into smaller, more manageable
subproblems to achieve a goal.
1. Identify the initial state (current situation) and the goal state (desired outcome).
Applications of MEA:
o Otherwise:
9. Once current_position == goal_position, print "Goal reached!" with the final position.
PROGRAM :-
# Grid dimensions (5x5)
GRID_SIZE = 5
if x_diff > 0:
else:
if y_diff > 0:
current_position[1] -= 1 # Move up
x, y = current_position
grid[x][y] = 'R'
print(" ".join(row))
print("\n")
OUTPUT :-
Current Position: [0, 0]
.R...
.....
.....
.....
.....
.....
.R...
.....
.....
.....
.....
..R..
.....
.....
.....
.....
.....
..R..
.....
.....
.....
.....
...R.
.....
.....
.....
.....
.....
...R.
.....
.....
.....
.....
....R
.....
.....
.....
.....
.....
....R
__________________________________________________________________________________________
THE END