TITLE Merged

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

PRACTICAL FILE

ARTIFICIAL INTELLIGENCE

SUBMITTED IN PARTIAL FULFILLMENT OF THE REQUIREMENT


FOR THE AWARD OF THE DEGREE OF

BACHELOR OF TECHNOLOGY

(Computer Science and Engineering)

SUBMITTED BY: SUBMITTED TO:

Chahat (2203413) Prof. Kamaljeet kaur


CSE-A1

Department Of Computer Science and Engineering

GURU NANAK DEV ENGINEERING COLLEGE

LUDHIANA,141006
Program 1: Introduction to python Interpreter.

The Python interpreter is an environment that reads and executes Python code line by line,
enabling you to run Python scripts and interact with the language in real-time. Here's a basic
guide on working with the Python interpreter and writing a simple introductory program.
Step 1: Opening the Python Interpreter
To access the Python interpreter:
1. Command Line: Open your terminal (Command Prompt on Windows, Terminal on
macOS or Linux).
2. Type python or python3 (depending on your Python installation) and press Enter.

>>>
Step 2: Writing Your First Python Program
Let’s start by writing a simple "Hello, World!" program. This is a standard first program for
learning any new programming language. In the Python interpreter, type the following line:

Step 3: Basic Arithmetic in the Interpreter


The Python interpreter can also be used as a calculator. For example, you can type:
python
Other examples include:
 Subtraction: 10 - 4
 Multiplication: 5 * 6
 Division: 15 / 3
Step 4: Exit the Interpreter
To exit the Python interpreter, you can type exit() or press Ctrl + D on Unix/macOS or Ctrl +
Z followed by Enter on Windows.
Putting It All Together
You can create a Python script instead of typing directly into the interpreter:
1. Create a file named hello.py.

This will display:

This covers a basic introduction to the Python interpreter and running a simple program!
Program 2: Programs to implement input output and control flow tools in
python.

1. Input/Output (I/O)
 Input: This is how you get data from the user. In Python, you can use the input()
function, which waits for the user to type something and then stores it as a string.
Inputs are essential for making interactive programs, allowing users to provide data
the program can process.
 Output: This is how you display data to the user. The print() function is commonly
used to display information on the screen. It can be used to show messages, results of
computations, or formatted data.
 Examples of Usage:
o Asking the user for their name, age, or favorite color.
o Displaying results like "Hello, [name]" or "Your age in 10 years will be
[calculated age]."

2. Control Flow Tools


Control flow allows you to define how your program executes, letting you make decisions,
repeat actions, and create logical sequences in your code. Here are the primary control flow
tools:
 Conditional Statements (if, elif, else):
o These statements help you make decisions in your code. You can set
conditions and specify different actions based on whether each condition is
true or false.
o Example Usage:
 Checking if a number is positive, negative, or zero.
 Verifying if a user-provided password is correct before allowing
access.
 Loops:
o For Loop: This loop is generally used to iterate over a sequence (like a list,
string, or range of numbers). It’s useful for performing actions a specific
number of times.
 Example Usage:
 Printing each item in a list.
 Calculating the sum of numbers from 1 to 100.
o While Loop: This loop repeats as long as a condition remains true, making it
useful for tasks that require indefinite repetition until a certain condition is
met.
 Example Usage:
 Asking the user to guess a number until they guess correctly.
 Continuously reading sensor data until a stop signal is detected.
 Break and Continue:
o break stops the current loop completely, which is useful when you want to exit
early based on a condition.
o continue skips the current iteration and moves to the next one, which can help
you ignore specific values in a loop.
o Example Usage:
 Using break to exit a loop when a user guesses the correct answer in a
game.
 Using continue to skip over even numbers in a loop that iterates
through numbers from 1 to 10.

3. Combining I/O and Control Flow


 Using input from the user, you can decide different paths in the code. For example,
you might ask for a user’s age and decide what message to display based on it.
 Loops combined with conditional statements allow for more complex tasks, like
validating multiple user inputs, performing calculations until a condition is met, or
iterating over lists while checking certain conditions.

Practical Scenarios:
 Calculator Program: Take two numbers and an operation type (like + or -) as input
and display the result based on the operation selected.
 Age Validator: Ask for a user's birth year, calculate their age, and use conditionals to
display if they are eligible to vote or not.
 Number Guessing Game: Generate a random number and prompt the user to guess
it, using loops to allow multiple attempts and conditional statements to give feedback
on each guess.
By combining these elements, you can create interactive and dynamic Python programs that
make decisions, process user data, and perform complex tasks repeatedly or conditionally.
OUTPUT:
Programs 3: Programs to implement different Data Structures in
Python.

Implement Arrays

array1=["Chahat 2203413"]

print(array1)

#CREATION OF AN ARRAY

array=[10,20,30,40]

print(array[2])

#Modify elements

array[1]=78

print(array)

# Append elements

array.append(48)

print(array)
OUTPUT:
Implement stack

class Stack:
def _init_(self):
self.items = []

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()
raise IndexError("Pop from an empty stack")

def peek(self):
if not self.is_empty():
return self.items[-1]
raise IndexError("Peek from an empty stack")

def is_empty(self):
return len(self.items) == 0

def size(self):
return len(self.items)

stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())

print(stack.peek())
OUTPUT:
Implement Queue

from collections import deque

class Queue:
def _init_(self):
self.items = deque()

def enqueue(self, item):


self.items.append(item)

def dequeue(self):
if not self.is_empty():
return self.items.popleft()
raise IndexError("Dequeue from an empty queue")

def is_empty(self):
return len(self.items) == 0

def size(self):
return len(self.items)

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue())
OUTPUT:
Program 5: Write a program to implement Breadth First search
for water jug problem.

from collections import deque

def bfs_water_jug_problem():
# Initial state: both jugs are empty
initial_state = (0, 0)

# Goal state: 4 gallons in the 5-gallon jug


goal = 4

# Queue to store the states to explore, initialized with the initial state
queue = deque([initial_state])

# Set to`` store visited states to avoid cycles


visited = set()

# To trace the path leading to the solution


parent = {}

# BFS Loop
while queue:
current_state = queue.popleft()
a, b = current_state

# Check if we have reached the goal state if


a == goal:
# Reconstruct the path from initial_state to the goal

path = [] while
current_state:
path.append(current_state)
current_state = parent.get(current_state)
path.reverse() return path

# Mark the current state as visited


visited.add(current_state)

# Generate all possible next states


possible_states = [
(5, b), # Fill 5-gallon jug
(a, 3), # Fill 3-gallon jug
(0, b), # Empty 5-gallon jug
(a, 0), # Empty 3-gallon jug
(a - min(a, 3 - b), b + min(a, 3 - b)), # Pour from 5-gallon to 3-gallon jug
(a + min(b, 5 - a), b - min(b, 5 - a)), # Pour from 3-gallon to 5-gallon jug
]
for next_state in possible_states: if
next_state not in visited:
parent[next_state] = current_state
queue.append(next_state)

# If no solution is found
return None

# Run the BFS function and print the solution path solution_path
= bfs_water_jug_problem()
if solution_path:

print("Chahat") print("URN: 2203413")


print("Solution path
found using BFS:") for step_no, (a, b) in
enumerate(solution_path):
print(f"Step {step_no + 1}: 5-gallon jug = {a} gallons, 3-gallon jug = {b} gallons")
else:
print("No solution found.")
OUTPUT:
Program 6: Write a program to implement Depth First search for
water jug problem.

def dfs_water_jug_problem():
# Initial state: both jugs are empty
initial_state = (0, 0)

# Goal state: 4 gallons in the 5-gallon jug


goal = 4

# Stack to store the states to explore, initialized with the initial state
stack = [(initial_state, [])]

# Set to store visited states to avoid cycles


visited = set()

# DFS Loop
while stack:
current_state, path = stack.pop()
a, b = current_state

# Add the current state to the path


path = path + [current_state]

# Check if we have reached the goal state


if a == goal: return path

# Mark the current state as visited


visited.add(current_state)
# Generate all possible next states
possible_states = [
(5, b), # Fill 5-gallon jug
(a, 3), # Fill 3-gallon jug
(0, b), # Empty 5-gallon jug
(a, 0), # Empty 3-gallon jug
(a - min(a, 3 - b), b + min(a, 3 - b)), # Pour from 5-gallon to 3-gallon jug
(a + min(b, 5 - a), b - min(b, 5 - a)), # Pour from 3-gallon to 5-gallon jug
]

for next_state in possible_states:


if next_state not in visited:
stack.append((next_state, path))

# If no solution is found
return None

# Run the DFS function and print the solution path


solution_path = dfs_water_jug_problem() if
solution_path:
print("Chahat")print("URN:
2203413")
print("Solution path found using DFS:") for
step_no, (a, b) in enumerate(solution_path):
print(f"Step {step_no + 1}: 5-gallon jug = {a} gallons, 3-gallon jug = {b} gallons")
else:
print("No solution found.")
Program 7: Write a Program to implement Best First
Search.
import heapq # Import heapq for priority
queue

class Graph: def


init (self):
self.edges = {} # Adjacency list representation of the graph
self.heuristics = {} # Heuristic values for each node

def add_edge(self, from_node, to_node, cost):


if from_node not in self.edges:
self.edges[from_node] = []
self.edges[from_node].append((to_node, cost))

def set_heuristic(self, node, value):


self.heuristics[node] = value

def best_first_search(self, start, goal):


# Priority queue initialized with the start node
priority_queue = [] heapq.heappush(priority_queue,
(self.heuristics[start], start))

visited = set() # Set to track visited nodes


path = [] # To keep track of the path

while priority_queue:
_, current_node = heapq.heappop(priority_queue) # Get node with the lowest
heuristic path.append(current_node)
if current_node == goal: # Goal check
return path

visited.add(current_node) # Mark the node as visited

for neighbor, cost in self.edges.get(current_node, []):


if neighbor not in visited:
heapq.heappush(priority_queue, (self.heuristics[neighbor], neighbor))

return None # If the goal cannot be reached

# Example usage graph


= Graph()

# Adding edges with associated costs


graph.add_edge('A', 'B', 1)
graph.add_edge('A', 'C', 3)
graph.add_edge('B', 'D', 2)
graph.add_edge('B', 'E', 4)
graph.add_edge('C', 'F', 5)
graph.add_edge('D', 'G', 2)
graph.add_edge('E', 'G', 1) graph.add_edge('F',
'G', 2)

# Setting heuristic values for nodes


graph.set_heuristic('A', 6)
graph.set_heuristic('B', 5) graph.set_heuristic('C',
4) graph.set_heuristic('D', 3)
OUTPUT:
graph.set_heuristic('E', 2) graph.set_heuristic('F',
4) graph.set_heuristic('G', 0) # Goal node
heuristic is 0

# Running the Best-First Search


start_node = 'A' goal_node =
'G'

result = graph.best_first_search(start_node, goal_node)

if result:
print("Chahat")
print("URN: 2203413") print("Solution path found
using Best-First Search:") for step_no, node in
enumerate(result): print(f"Step {step_no + 1}:
{node}") else:
print("No solution found.")
OUTPUT:
Program 8: Write a program to implementA*algorithm.
from queue import PriorityQueue

# Define the graph using an adjacency list def


create_graph():
return {
'A': {'B': 1, 'C': 3},
'B': {'A': 1, 'D': 1, 'E': 3},
'C': {'A': 3, 'F': 1},
'D': {'B': 1, 'G': 2},
'E': {'B': 3, 'G': 5},
'F': {'C': 1, 'G': 2},
'G': {}
}

# Heuristic function (Manhattan distance, for example)


def heuristic(node, goal):
h={
'A': 6,
'B': 5,
'C': 4,
'D': 4,
'E': 3,
'F': 2,
'G': 0 # The heuristic for the goal node is always 0
}
return h[node]

def a_star_algorithm(graph, start, goal):


# Priority queue to store nodes with their priority as the total cost
open_set = PriorityQueue() open_set.put((0, start))

# Dictionaries to store the cost of the path and the parent of each node
g_costs = {node: float('inf') for node in graph} g_costs[start] = 0

parents = {node: None for node in graph}

while not open_set.empty():


_, current = open_set.get()

if current == goal:
path = []
while current:
path.append(current)
current = parents[current] return
path[::-1] # Return reversed path

for neighbor, cost in


graph[current].items(): tentative_g_cost
= g_costs[current] + cost

if tentative_g_cost < g_costs[neighbor]:


g_costs[neighbor] = tentative_g_cost total_cost =
tentative_g_cost + heuristic(neighbor, goal)
open_set.put((total_cost, neighbor)) parents[neighbor]
= current
return None # If there is no path

# Example usage graph = create_graph() start_node =


'A' goal_node = 'G' path = a_star_algorithm(graph,
start_node, goal_node)
print("Chahat")
print("URN-2203413") print("Path from", start_node,
"to", goal_node, ":", path)
Output:
Program 9: Write a Program to implement tic tac toe game for 0 and X.

# Function to print the Tic-Tac-Toe boarddef


print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)

print("Chahat (2203413)")
# Function to check for a win
def check_win(board, player):
# Check rows, columns, and diagonals for a win
for i in range(3):
if all([cell == player for cell in board[i]]) or all([board[j][i] == player for j in range(3)]):
return True
if all([board[i][i] == player for i in range(3)]) or all([board[i][2 - i] == player for i in
range(3)]):
return True
return False

# Function to check for a tie


def check_tie(board):
return all([cell != " " for row in board for cell in row])

# Main game function


def play_game():
# Initialize an empty 3x3 board
board = [[" " for _ in range(3)] for _ in range(3)]

current_player = "X"

while True:
print_board(board)
print(f"Player {current_player}, enter your move (row and column): ")

# Get the player's movetry:


row, col = map(int, input().split())
except ValueError:
print("Invalid input. Please enter row and column as two numbers separated by a
space.")
continue

# Check if the move is valid


if row < 0 or row > 2 or col < 0 or col > 2 or board[row][col] != " ":
print("Invalid move. Try again.")
continue

# Make the move board[row][col] =


current_player

# Check for a win


if check_win(board, current_player):
print_board(board)
print(f"Player {current_player} wins!")
break

# Check for a tie


if check_tie(board):
print_board(board)

print("It's a tie!")
break

# Switch to the other player


current_player = "O" if current_player == "X" else "X"

# Start the game


play_game()
OUTPUT:
Program 10: Write a Program to construct a Bayesian network from given
data.

from pgmpy.models import BayesianNetwork


from pgmpy.estimators import ParameterEstimator, MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
from pgmpy.factors.discrete import TabularCPD
import pandas as pd
# Sample data to construct the Bayesian Network
data = pd.DataFrame(data={
'Rain': [1, 1, 0, 1, 0, 0, 1, 1, 0, 0],
'Sprinkler': [0, 1, 1, 1, 1, 0, 0, 1, 0, 0],
'Grass Wet': [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
})

# Define the structure of the Bayesian Network


# Here we assume 'Sprinkler' and 'Rain' are the causes of 'Grass Wet'
model = BayesianNetwork([('Rain', 'Grass Wet'), ('Sprinkler', 'Grass Wet')])

# Estimate the Conditional Probability Distributions (CPDs) from the data


model.fit(data, estimator=MaximumLikelihoodEstimator)

# Print the CPDs


for cpd in model.get_cpds():
print(f"CPD of {cpd.variable}:")
print(cpd)

# Inference: Predicting the probability of 'Grass Wet' given evidence

infer = VariableElimination(model)
print("\nProbability of Grass Wet when Rain=1 and Sprinkler=0:")
query_result = infer.query(variables=['Grass Wet'], evidence={'Rain': 1, 'Sprinkler': 0})
print(query_result)
OUTPUT:
Program 11: Write a Program to infer from the Bayesian network.

# Install pgmpy in Google Colab or similar environments if needed


# !pip install pgmpy

from pgmpy.models import BayesianNetwork


from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
import pandas as pd

# Sample data to construct the Bayesian Network


data = pd.DataFrame({
'Rain': [1, 1, 0, 1, 0, 0, 1, 1, 0, 0],
'Sprinkler': [0, 1, 1, 1, 1, 0, 0, 1, 0, 0],
'Grass Wet': [1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
})

# Define the structure of the Bayesian Network


# Edges mean that Rain and Sprinkler influence Grass Wet
model = BayesianNetwork([('Rain', 'Grass Wet'), ('Sprinkler', 'Grass Wet')])

# Fit the model to the data to estimate probabilities


model.fit(data, estimator=MaximumLikelihoodEstimator)

# Print the learned CPDs


print("Conditional Probability Distributions (CPDs) of the model:")
for cpd in model.get_cpds():
print(cpd)
OUTPUT:
# Initialize the inference method
infer = VariableElimination(model)

# Perform inference: Probability of Grass Wet given evidence


# Example 1: Probability of Grass Wet when Rain=1 and Sprinkler=0
print("\nQuery: Probability of Grass Wet when Rain=1 and Sprinkler=0")
query_result = infer.query(variables=['Grass Wet'], evidence={'Rain': 1, 'Sprinkler': 0})
print(query_result)

# Example 2: Probability of Grass Wet when Rain=0 and Sprinkler=1


print("\nQuery: Probability of Grass Wet when Rain=0 and Sprinkler=1")
query_result = infer.query(variables=['Grass Wet'], evidence={'Rain': 0, 'Sprinkler': 1})
print(query_result)

# Example 3: Probability of Sprinkler given Grass Wet = 1


print("\nQuery: Probability of Sprinkler when Grass Wet=1")
query_result = infer.query(variables=['Sprinkler'], evidence={'Grass Wet': 1})
print(query_result)

You might also like