0% found this document useful (0 votes)
35 views8 pages

AI LAB RPOGRAMS 1 To 6

AI programs

Uploaded by

Sohaib Sayed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views8 pages

AI LAB RPOGRAMS 1 To 6

AI programs

Uploaded by

Sohaib Sayed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Artificial Intelligence Using Python

1. Write a Program to Implement Breadth First Search using Python.


2. Write a Program to Implement Depth First Search using Python
3. Write a Program to implement a tower of Hanoi using python.
4. Write a Program to implement a simple chatbot using python.
5. Write a Program to Implement a Linear Regression using Python.
6. Write a Program to implement Hangman Game using python.

 Write a Program to Implement Breadth First Search using Python.

import matplotlib.pyplot as plt


import networkx as nx
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling
# Visualizing the graph
G = nx.Graph(graph)
pos = nx.spring_layout(G) # Positions for all nodes
nx.draw(G, pos, with_labels=True, node_size=1000, node_color="lightblue", font_size=12,
font_weight="bold")
plt.title("Graph Visualization")
plt.show()

Output of Program:
Following is the Breadth-First Search
537248

 Write a Program to Implement Depth First Search using Python

import matplotlib.pyplot as plt


import networkx as nx
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
# Visualizing the graph
G = nx.Graph(graph)
pos = nx.spring_layout(G) # Positions for all nodes
nx.draw(G, pos, with_labels=True, node_size=1000, node_color="lightblue", font_size=12,
font_weight="bold")
plt.title("Graph Visualization")
plt.show()

Output of Program:
Following is the Depth-First Search
5
3
2
4
8
7

 Write a Program to implement a tower of Hanoi using python.


# Creating a recursive function
def tower_of_hanoi(disks, source, auxiliary, target):
if (disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
# function call itself
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))
tower_of_hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter the number of disks: '))
# We are referring source as A, auxiliary as B, and target as C
tower_of_hanoi(disks, 'A', 'B', 'C') # Calling the function

Output of Program :
Enter the number of disks: 3
Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.
 Write a Program to implement a simple chatbot using python.

print("How are you?")


print("Are you working?")
print("What is your name?")
print("what did you do yesterday?")
print("Quit")

while True:
question = input("Enter one question from above list:")
question = question.lower()
if question in ['hi']:
print("Hello")
elif question in ['how are you?','how do you do?']:
print("I am fine")
elif question in ['are you working?','are you doing any job?']:
print("yes. I'am working in KLU")
elif question in ['what is your name?']:
print("My name is Emilia")
name=input("Enter your name?")
print("Nice name and Nice meeting you", name)
elif question in ['what did you do yesterday?']:
print("I saw Bahubali 5 times")
elif question in ['quit']:
break
else:
print("I don't understand what you said")

Output Program :
How are you?
Are you working?
What is your name?
what did you do yesterday?
Quit
Enter one question from above list:Hi
Hello
Enter one question from above list:How are you?
I am fine
Enter one question from above list:WHat is your Name?
My name is Emilia
Enter one question from above list:what did you do yesterday?
I saw Bahubali 5 times
Enter one question from above list:time
I don't understand what you said
Enter one question from above list:quit

 Write a Program to Implement a Linear Regression using Python.

Pgm 5: Linear regression


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Sample data
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) # Feature matrix (reshape to a column vector)
y = np.array([2, 3, 4, 5, 6]) # Target values

# Create and fit the linear regression model


model = LinearRegression()
model.fit(X, y)

# Predictions
y_pred = model.predict(X)

# Plotting the data and the linear regression line


plt.scatter(X, y, color='blue', label='Actual data')
plt.plot(X, y_pred, color='red', label='Linear regression line')
plt.title('Linear Regression')
plt.xlabel('X')
plt.ylabel('y')
plt.legend()
plt.show()

# Printing coefficients
print('Intercept:', model.intercept_)
print('Slope:', model.coef_[0])

 Write a Program to implement Hangman Game using python.

import time
from time import sleep
name = input("Enter Your Name:")
print( "Hello" + name)
print("Get ready!!")
print ("")
time.sleep(1)
print ("Let us play Hangman!!")
time.sleep(0.5)
word = "Flower"
wrd = ''
chance = 10
while chance > 0:
failed = 0
for char in word:
if char in wrd:
print (char)
else:
print( "_")
failed += 1
if failed == 0:
print( "You Won!!Congratulations!!" )
break
guess = input("Guess a Letter:")
wrd = wrd+guess
if guess not in word:
chance -= 1
print ("Wrong Guess! Try Again")
print ("You have", + chance, 'more turn' )
if chance == 0:
print ("You Lose! Better Luck Next Time" )

Output Program :
Enter Your Name:Rohit
Hello Rohit
Get ready!!

Let us play Hangman!!


_
_
_
_
_
_

Guess a Letter:e
_
_
_
_
e
_
Guess a Letter:l
_
l
_
_
e
_
Guess a Letter:o
_
l
o
_
e
_
Guess a Letter:w
_
l
o
w
e
_
Guess a Letter:r
_
l
o
w
e
r
Guess a Letter:f
Wrong Guess! Try Again
You have 9 more turn
_
l
o
w
e
r
Guess a Letter:f
Wrong Guess! Try Again
You have 8 more turn
_
l
o
w
e
r
Guess a Letter:F
F
l
o
w
e
r
You Won!!Congratulations!!

You might also like