TITLE Merged
TITLE Merged
TITLE Merged
ARTIFICIAL INTELLIGENCE
BACHELOR OF TECHNOLOGY
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:
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]."
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 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
class Queue:
def _init_(self):
self.items = deque()
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.
def bfs_water_jug_problem():
# Initial state: both jugs are empty
initial_state = (0, 0)
# Queue to store the states to explore, initialized with the initial state
queue = deque([initial_state])
# BFS Loop
while queue:
current_state = queue.popleft()
a, b = current_state
path = [] while
current_state:
path.append(current_state)
current_state = parent.get(current_state)
path.reverse() return path
# 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:
def dfs_water_jug_problem():
# Initial state: both jugs are empty
initial_state = (0, 0)
# Stack to store the states to explore, initialized with the initial state
stack = [(initial_state, [])]
# DFS Loop
while stack:
current_state, path = stack.pop()
a, b = current_state
# If no solution is found
return None
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
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
# 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
if current == goal:
path = []
while current:
path.append(current)
current = parents[current] return
path[::-1] # Return reversed path
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
current_player = "X"
while True:
print_board(board)
print(f"Player {current_player}, enter your move (row and column): ")
print("It's a tie!")
break
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.