0% found this document useful (0 votes)
19 views

Ai 3

Program code for bca

Uploaded by

hruthikaraga
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)
19 views

Ai 3

Program code for bca

Uploaded by

hruthikaraga
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

1.

Write a program to implement Depth Limit Search


def depth_limit_search(array, depth_limit):
def dls_helper(arr, current_depth):

if current_depth > depth_limit:


return

for element in arr:


if isinstance(element, list):
print(f"At depth {current_depth}: Encountered nested list,
diving deeper...")
dls_helper(element, current_depth + 1)
else:
print(f"At depth {current_depth}: Processing element:
{element} ")
# Start the depth-limited search with the initial depth of 0
dls_helper(array, 0)
# Example usage
nested_array = [10,20,[3],[5]]
depth_limit = 2
depth_limit_search(nested_array, depth_limit)

2. Write a program to implement Simple Chatbot Program using python

print("Welcome to the simple chatbot. Type 'bye' to exit.")


while True:
user_input = input("You: ")
if user_input.lower() == "bye":
print("Chatbot: Goodbye!")
break
def chatbot_response(user_input):
# Convert the input to lowercase to make the bot case insensitive
user_input = user_input.lower()
# Simple keyword-based responses
if "hello" in user_input or "hi" in user_input:
return "Hello! How can I help you today?"
elif "how are you" in user_input:
return "I'm just a bot, but I'm here to help you! How can I assist
you?"
elif "name" in user_input:
return "I am a chatbot What's your name?"
elif "goodbye" in user_input or "bye" in user_input:
return "Have a great day!"
else:
return "I'm sorry, I don't understand that. Can you rephrase?"
# Main loop to interact with the chatbot
response = chatbot_response(user_input)
print("Chatbot:", response)

3. Write a program to implement Iterative deepening depth-first search python


from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DLS(self, src, target, maxDepth):
if src == target: return True
if maxDepth <= 0: return False
for i in self.graph[src]:
if (self.DLS(i, target, maxDepth - 1)):
return True
return False
def IDDFS(self, src, target, maxDepth):
for i in range(maxDepth):
if (self.DLS(src, target, i)):
return True
return False
g = Graph (7);
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 3)
g.addEdge(1, 4)
g.addEdge(2, 5)
g.addEdge(2, 6)
g.addEdge(5,10)
target = 10
maxDepth = 4
src = 0
if g.IDDFS(src, target, maxDepth) == True:
print("Target is reachable within max depth")
else:
print("Target is NOT reachable within max depth, increase depth limit")

4. Write a program to implement Hill climbing algorithm using python


n=4
ary = [ [0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0] ]
completed = [0] * n
def least(c):
global cost
min_cost = float('inf')
kmin = 0
nc = 999
for i in range(n):
if (ary[c][i] != 0) and (completed[i] == 0):
if ary[c][i] + ary[i][0] < min_cost:
if ary[c][i] < min_cost:
min_cost = ary[c][i] + ary[i][0]
kmin = ary[c][i]
nc = i
if min_cost != float('inf'):
cost += kmin
return nc
def hill_climbing(city):
global cost
completed[city] = 1
print(f"{city + 1}--->", end='')
ncity = least(city)
if ncity == 999:
ncity = 0
print(ncity + 1)
cost += ary[city][ncity]
return
hill_climbing(ncity)
cost = 0
print("\n\nThe Path is:\n")
hill_climbing(0) # starting vertex is 0
print(f"\n\nMinimum cost is {cost}\n")

OUTPUT

The Path is:

1--->2--->4--->3--->1

Minimum cost is 80

5. Write a program to implement Forward Chaining example

class Rule:
def __init__(self, premises, conclusion):
self.premises = premises
self.conclusion = conclusion
# Knowledge base
rules = [
Rule(["A"], "B"),
Rule(["B", "C"], "D"),
Rule(["D"], "E"),
Rule(["F"], "C"),
Rule(["A"],"z")
]
def forward_chaining(knowledge_base, query):
inferred = set()
agenda = [query]

while agenda:
fact = agenda.pop(0)
if fact not in inferred:
inferred.add(fact)
matching_rules = [rule for rule in knowledge_base if all(premise
in inferred for premise in rule.premises)]
for rule in matching_rules:
agenda.append(rule.conclusion)
return inferred
# Test forward chaining
print("Forward Chaining:")
print("Inferred facts:", forward_chaining(rules, "A"))

OUTPUT:

Forward Chaining:

Inferred facts: {'A', 'z', 'B'}

6. Write a program to implement Backward Chaining example

class Rule:
def __init__(self, premises, conclusion):
self.premises = premises
self.conclusion = conclusion
# Knowledge base
rules = [
Rule(["A"], "B"),
Rule(["B", "C"], "D"),
Rule(["D"], "E"),
Rule(["F"], "C") ]

def backward_chaining(knowledge_base, query):


inferred = set()

def ask(fact):
# If fact is already inferred, return True
if fact in inferred:
return True

# Find rules whose conclusion is fact


matching_rules = [rule for rule in knowledge_base if rule.conclusion
== fact]

# Try to prove premises of matching rules


for rule in matching_rules:
if all(ask(premise) for premise in rule.premises):
inferred.add(fact)
return True

return False

# Initialize inferred with known facts


known_facts = {"A","F"} #TRUE
#known_facts = {"A"} #FALSE
inferred.update(known_facts)

# Start the backward chaining process


can_prove = ask(query)
return can_prove, inferred

# Test backward chaining


print("\nBackward Chaining:")
can_prove, inferred_facts = backward_chaining(rules, "E")
print("Can prove E?", can_prove)
print("Inferred facts:", inferred_facts)

OUTPUT 1:

Backward Chaining:

Can prove E? True

Inferred facts: {'C', 'B', 'E', 'F', 'D', 'A'}

OUTPUT-2:

Backward Chaining:

Can prove E? False

Inferred facts: {'B', 'A'}

7. Write a program to implement Find-S algorithm using python

def find_s_algorithm(examples):
hypothesis = None
for features, label in examples:
if label == 1:
if hypothesis is None:
hypothesis = features.copy()
else:
for i in range(len(hypothesis)):
if hypothesis[i] != features[i]:
hypothesis[i] = '?'
return hypothesis
# Example usage
examples = [
(['Sunny', 'Warm', 'Normal', 'Strong', 'Warm', 'Same'], 1),
(['Sunny', 'Warm', 'High', 'Strong', 'Warm', 'Same'], 1),
(['Rainy', 'Cold', 'High', 'Strong', 'Warm', 'Change'], 0),
(['Sunny', 'Warm', 'High', 'Strong', 'Cool', 'Change'], 1)
]
hypothesis = find_s_algorithm(examples)
print("Most specific hypothesis:", hypothesis)

OUTPUT: Most specific hypothesis: ['Sunny', 'Warm', '?', 'Strong', '?', '?']
8. Write a program to implement Template matching
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('doraemon.jpg', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with
os.path.exists()"
img2 = img.copy()
template = cv.imread('D1.jpg', cv.IMREAD_GRAYSCALE)
assert template is not None, "file could not be read, check with
os.path.exists()"
w, h = template.shape[::-1]
# All the 6 methods for comparison in a list
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED']
#['cv.TM_CCORR', 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF',
#'cv.TM_SQDIFF_NORMED']
for meth in methods:
img = img2.copy()
method = eval(meth)
res = cv.matchTemplate(img,template,method)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
# If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0] + w, top_left[1] + h)
cv.rectangle(img,top_left, bottom_right, 255, 2)
plt.subplot(121),plt.imshow(res,cmap = 'gray')
plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img,cmap = 'gray')
plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
plt.suptitle(meth)
plt.show()

OUTPUT:

9. Write a program to implement Hough circle transformation

import numpy as np
import cv2 as cv
img = cv.imread('c.png', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
img = cv.medianBlur(img, 5)
cimg = cv.cvtColor(img, cv.COLOR_GRAY2BGR)

circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1, 8, param1=100,


param2=30,minRadius=1, maxRadius=45)
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# draw the outer circle
cv.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# draw the center of the circle
cv.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)

cv.imshow('detected circles', cimg)


cv.waitKey(0)
cv.destroyAllWindows()

OUTPUT:

10. Write a program to implement Multiple Linear Regression Model using python

import numpy as np
import matplotlib as mpl
#from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

def generate_dataset(n):
x = []
y = []
random_x1 = np.random.rand()
random_x2 = np.random.rand()
for i in range(n):
x1 = i
x2 = i / 2 + np.random.rand() * n
x.append([1, x1, x2])
y.append(random_x1 * x1 + random_x2 * x2 + 1)
return np.array(x), np.array(y)
x, y = generate_dataset(50)
mpl.rcParams['legend.fontsize'] = 12
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.scatter(x[:, 1], x[:, 2], y, label='Y', s=5,edgecolors='red')
ax.legend( )
ax.view_init(45, 0)
plt.show()

OUTPUT:

You might also like