Final
Final
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
Output:
2. Python Program on problem solving by searching: Depth-First Search.
graph = {
'A' : ['B','C','D'], 'B' : ['E', 'F'], 'C' : [], 'D' : ['G','H'], 'E' : [], 'F' : [],
'G' : ['I','J'], 'I' : [], 'J' : ['K'], 'K' : [], 'H' : []
}
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, 'A')
Output:
3. Python Program on problem solving by searching: Greedy best-first
Search.
import heapq
graph = {
'A': [('B'), ('C')], 'B': [('D'), ('E')], 'C': [('F')], 'D': [('G'), ('I')], 'E': [('H')],
'F': [], 'G': [], 'H': [], 'I': []
}
heuristic = {
'A':10, 'B':8, 'C':7, 'D':6, 'E':4, 'F':5, 'G':3, 'H':2, 'I':0
}
def best_first_search(graph,start,goal,heuristic):
frontier = [(heuristic[start], start)]# priority queue of(priority, node)
came_from = {}
came_from[start] = None
while frontier:
_, current = heapq.heappop(frontier)# node with lowest heuristic value
if current == goal:
break
for neighbor in graph[current]:
if neighbor not in came_from:
priority = heuristic[neighbor]
heapq.heappush(frontier, (priority, neighbor))
came_from[neighbor] = current
return came_from
start_node ='A'
goal_node ='I'
came_from = best_first_search(graph, start_node, goal_node, heuristic)
Output:
4. Python Program on problem solving by searching: A* Search.
if n == None:
print('Path does not exist!')
return None
def heuristic(n):
H_dist = {
'A': 11, 'B': 6,'C': 5,'D': 7, 'E': 3, 'F': 6, 'G': 5, 'H': 3, 'I': 1, 'J': 0
}
return H_dist[n]
aStarAlgo('A', 'J')
Output:
5. Python Program on problem solving by searching: AO* Search.
class Graph:
def __init__(self, graph, heuristicNodeList, startNode): #instantiate graph object
with graph topology, heuristic values, start node
self.graph = graph
self.H=heuristicNodeList
self.start=startNode
self.parent={}
self.status={}
self.solutionGraph={}
# Example dataset
data = {
'feature1': [1, 2, 3, 4, 5],
'feature2': [3, 5, 7, 8, 9],
'target': [4, 7, 10, 12, 14]
}
df = pd.DataFrame(data)
X = df[['feature1', 'feature2']]
y = df['target']
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_squared_error
# Example dataset
data = {
'year': [2010, 2011, 2012, 2013, 2014],
'mileage': [50000, 40000, 30000, 20000, 10000],
'price': [15000, 14000, 13000, 12000, 11000]
}
df = pd.DataFrame(data)
X = df[['year', 'mileage']]
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
model = DecisionTreeRegressor()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
print("Predictions:", y_pred)
Output:
8. Python program of weather prediction model that predicts whether or not
there’ll be rain on a particular day.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'temperature': [30, 25, 27, 35, 20],
'humidity': [70, 65, 80, 90, 60],
'rain': [1, 1, 1, 0, 0] # 1 for rain, 0 for no rain
}
df = pd.DataFrame(data)
X = df[['temperature', 'humidity']]
y = df['rain']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_pred = [1 if p >= 0.5 else 0 for p in y_pred]
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Output:
10. Python program to classify the emails as spam or not spam.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
# Example dataset
data = {
'email': ['buy now', 'limited offer', 'meeting at 3', 'project deadline', 'win a
prize'],
'label': [1, 1, 0, 0, 1] # 1 for spam, 0 for not spam
}
df = pd.DataFrame(data)
X = df['email']
y = df['label']
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(X)
model = MultinomialNB()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Predictions:", y_pred)
Output:
11. Python program that demonstrate how to classify flower using a Support
vector machine classifier.
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# Sample data: [height (cm), weight (kg)]
X = np.array([
[150, 45], [160, 55], [170, 65], [180, 75], [190, 85],
[160, 50], [170, 60], [180, 70], [190, 80], [200, 90]
])
# Labels: 0 for class 0 (shorter/lighter), 1 for class 1 (taller/heavier)
y = np.array([0, 0, 0, 1, 1, 0, 0, 1, 1, 1])
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Create the MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(5,), max_iter=1000,
random_state=42)
# Train the classifier
clf.fit(X_train, y_train)
# Make predictions
y_pred = clf.predict(X_test)
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
# Print the results
print("Testing inputs (X_test):")
print(X_test)
print("Actual labels (y_test):")
print(y_test)
print("Predicted labels (y_pred):")
print(y_pred)
print("Accuracy:", accuracy)
Output:
13. Python program using speech recognition library to perform speech
recognition.
import speech_recognition as sr
# Initialize recognizer class (for recognizing the speech)
r = sr.Recognizer()
Output
Hi Siri.