Ai LP-II Lab Manual
Ai LP-II Lab Manual
BFS is one of the traversing algorithm used in graphs. This algorithm is implemented
using a queue data structure. In this algorithm, the main focus is on the vertices of
the graph. Select a starting node or vertex at first, mark the starting node or vertex
as visited and store it in a queue. Then visit the vertices or nodes which are adjacent
to the starting node, mark them as visited and store these vertices or nodes in a queue.
Repeat this process until all the nodes or vertices are completely visited.
Advantages of BFS
Disadvantages of BFS
1. The execution time of this algorithm is very slow because the time
complexity of this algorithm is exponential.
2. This algorithm is not useful when large graphs are used.
Explanation:
1. Create a graph.
2. Initialize a starting node.
3. Send the graph and initial node as parameters to the bfs function.
4. Mark the initial node as visited and push it into the queue.
5. Explore the initial node and add its neighbours to the queue and remove
the initial node from the queue.
6. Check if the neighbours node of a neighbouring node is already visited.
7. If not, visit the neighbouring node neighbours and mark them as visited.
8. Repeat this process until all the nodes in a graph are visited and the queue
becomes empty.
Output:
import collections
# BFS algorithm
def bfs(graph, root):
while queue:
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print
A standard DFS implementation puts each vertex of the graph into one of two
categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list to the top of the stack.
Let's see how the Depth First Search algorithm works with an example. We use an
undirected graph with 5 vertices.
Undirected graph with 5 vertices
We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and
putting all its adjacent vertices in the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes.
Since 0 has already been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so
we have completed the Depth First Traversal of the graph.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we have completed
The time complexity of the DFS algorithm is represented in the form of O(V + E) ,
import java.util.*;
class Graph {
private LinkedList<Integer> adjLists[];
private boolean visited[];
// Graph creation
Graph(int vertices) {
adjLists = new LinkedList[vertices];
visited = new boolean[vertices];
// Add edges
void addEdge(int src, int dest) {
adjLists[src].add(dest);
}
// DFS algorithm
void DFS(int vertex) {
visited[vertex] = true;
System.out.print(vertex + " ");
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);
g.DFS(2);
}
}
# DFS algorithm
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
dfs(graph, '0')
A* Search
A* search is the most commonly known form of best-first search. It
uses heuristic function h(n), and cost to reach the node n from the
start state g(n). It has combined features of UCS and greedy best-
first search, by which it solve the problem efficiently. A* search
algorithm finds the shortest path through the search space using the
heuristic function. This search algorithm expands less search tree
and provides optimal result faster. A* algorithm is similar to UCS
except that it uses g(n)+h(n) instead of g(n).
In A* search algorithm, we use search heuristic as well as the cost
to reach the node. Hence we can combine both costs as following,
and this sum is called as a fitness number.
Algorithm of A* search:
Step1: Place the starting node in the OPEN list.
Step 2: Check if the OPEN list is empty or not, if the list is empty
then return failure and stops.
Step 3: Select the node from the OPEN list which has the smallest
value of evaluation function (g+h), if node n is goal node then return
success and stop, otherwise
Step 4: Expand node n and generate all of its successors, and put n
into the closed list. For each successor n', check whether n' is already
in the OPEN or CLOSED list, if not then compute evaluation
function for n' and place into Open list.
Step 5: Else if node n' is already in OPEN and CLOSED, then it
should be attached to the back pointer which reflects the lowest g(n')
value.
Step 6: Return to Step 2.
Advantages:
1. A* search algorithm is the best algorithm than other search
algorithms.
2. A* search algorithm is optimal and complete.
3. This algorithm can solve very complex problems.
Disadvantages:
1. It does not always produce the shortest path as it mostly
based on heuristics and approximation.
2. A* search algorithm has some complexity issues.
3. The main drawback of A* is memory requirement as it keeps
all generated nodes in the memory, so it is not practical for
various large-scale problems.
dict_gn=dict(
Arad=dict(Zerind=75,Timisoara=118,Sibiu=140),
Bucharest=dict(Urziceni=85,Giurgiu=90,Pitesti=101,Fagaras=211),
Craiova=dict(Drobeta=120,Pitesti=138,Rimnicu=146),
Drobeta=dict(Mehadia=75,Craiova=120),
Eforie=dict(Hirsova=86),
Fagaras=dict(Sibiu=99,Bucharest=211),
Giurgiu=dict(Bucharest=90),
Hirsova=dict(Eforie=86,Urziceni=98),
Iasi=dict(Neamt=87,Vaslui=92),
Lugoj=dict(Mehadia=70,Timisoara=111),
Mehadia=dict(Lugoj=70,Drobeta=75),
Neamt=dict(Iasi=87),
Oradea=dict(Zerind=71,Sibiu=151),
Pitesti=dict(Rimnicu=97,Bucharest=101,Craiova=138),
Rimnicu=dict(Sibiu=80,Pitesti=97,Craiova=146),
Sibiu=dict(Rimnicu=80,Fagaras=99,Arad=140,Oradea=151),
Timisoara=dict(Lugoj=111,Arad=118),
Urziceni=dict(Bucharest=85,Hirsova=98,Vaslui=142),
Vaslui=dict(Iasi=92,Urziceni=142),
Zerind=dict(Oradea=71,Arad=75)
)
import queue as Q
#from RMP import dict_gn
#from RMP import dict_hn
start='Arad'
goal='Bucharest'
result=''
def get_fn(citystr):
cities=citystr.split(" , ")
hn=gn=0
for ctr in range(0, len(cities)-1):
gn=gn+dict_gn[cities[ctr]][cities[ctr+1]]
hn=dict_hn[cities[len(cities)-1]]
return(hn+gn)
def expand(cityq):
global result
tot, citystr, thiscity=cityq.get()
if thiscity==goal:
result=citystr+" : : "+str(tot)
return
for cty in dict_gn[thiscity]:
cityq.put((get_fn(citystr+" , "+cty), citystr+" , "+cty, cty))
expand(cityq)
def main():
cityq=Q.PriorityQueue()
thiscity=start
cityq.put((get_fn(start),start,thiscity))
expand(cityq)
print("The A* path with the total is: ")
print(result)
main()
"""
OUTPUT:
The A* path with the total is:
Arad , Sibiu , Rimnicu , Pitesti , Bucharest : : 418
"""
Pseudocode
T = ∅;
M = { 1 };
while (M ≠ N)
let (m, n) be the lowest cost edge such that m ∈ M and n ∈ N - M;
T = T ∪ {(m, n)}
M = M ∪ {n}
Here we create two sets of nodes i.e M and M-N. M set contains the list of nodes that have
been visited and the M-N set contains the nodes that haven’t been visited. Later, we will move
each node from M to M-N after each step by connecting the least weight edge.
Example
Let us consider the below-weighted graph
Later we will consider the source vertex to initialize the algorithm
Now, we will choose the shortest weight edge from the source vertex and add it to finding the
spanning tree.
Then, choose the next nearest node connected with the minimum edge and add it to the
solution. If there are multiple choices then choose anyone.
Continue the steps until all nodes are included and we find the minimum spanning tree.
# Prim's Algorithm in Python
INF = 9999999
# number of vertices in graph
N=5
#creating graph by adjacency matrix method
G = [[0, 19, 5, 0, 0],
[19, 0, 5, 9, 2],
[5, 5, 0, 1, 6],
[0, 9, 1, 0, 1],
[0, 2, 6, 1, 0]]
selected_node = [0, 0, 0, 0, 0]
no_edge = 0
selected_node[0] = True
minimum = INF
a=0
b=0
for m in range(N):
if selected_node[m]:
for n in range(N):
if ((not selected_node[n]) and G[m][n]):
# not in selected and there is an edge
if minimum > G[m][n]:
minimum = G[m][n]
a=m
b=n
print(str(a) + "-" + str(b) + ":" + str(G[a][b]))
selected_node[b] = True
no_edge += 1
Time Complexity:
The running time for prim’s algorithm is O(VlogV + ElogV) which is equal to O(ElogV)
because every insertion of a node in the solution takes logarithmic time. Here, E is the number
of edges and V is the number of vertices/nodes. However, we can improve the running time
complexity to O(E + logV) of prim’s algorithm using Fibonacci Heaps.
Applications
Prim’s algorithm is used in network design
It is used in network cycles and rail tracks connecting all the cities
Prim’s algorithm is used in laying cables of electrical wiring
Prim’s algorithm is used in irrigation channels and placing microwave towers
It is used in cluster analysis
Prim’s algorithm is used in gaming development and cognitive science
Pathfinding algorithms in artificial intelligence and traveling salesman problems make use of
prim’s algorithm.
Conclusion
As we studied, the minimum spanning tree has its own importance in the real world, it is
important to learn the prim’s algorithm which leads us to find the solution to many problems.
When it comes to finding the minimum spanning tree for the dense graphs, prim’s algorithm is
the first choice.
Group-B
4. Implement a solution for a Constraint Satisfaction Problem
using Branch and Bound and Backtracking for n-queens
problem or a graph coloring problem
#include<bits/stdc++.h>
using namespace std;
int board[8][8]
int n
// function to print solution
void printSolution(int board[n][n])
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{ cout<<board[i][j]<<" ";
}
cout<<endl;
}
}
return true;
}
board[i][col] = 0;
rowLook[i] = false;
slashDiagolLook[slashDiagnol[i][col]] = false;
backSlashDiagnolLook[backSlashDiagnol[i][col]] = false;
}
}
/* This function solves the N Queen problem using Branch and Bound. It mainly uses
solveNQueensUtil() to solve the problem. It returns false if queens cannot be placed,
otherwise return true and prints placement of queens in the form of 1s. Please note that
there may be more than one solutions, this function prints one of the feasible solutions.*/
bool solveNQueens(n)
{
memset(board, 0, sizeof(board));
// helper matrices
int slashDiagnol[n][n];
int backSlashDiagnol[n][n];
// solution found
printSolution(board);
return true;
}
// main function
int main()
{
cin>>n; // can take any size from 0 to 8
solveNQueens(n);
return 0;
}
Output-
for (n = 8)
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
Graph coloring problem’s solution using backtracking algorithm
Graph coloring
The graph coloring problem is to discover whether the nodes of the graph G can
be covered in such a way, that no two adjacent nodes have the same color yet
only m colors are used. This graph coloring problem is also known as M-
colorability decision problem.
The M – colorability optimization problem deals with the smallest integer m for
which the graph G can be colored. The integer is known as a chromatic number
of the graph.
Here, it can also be noticed that if d is the degree of the given graph, then it can
be colored with d+ 1 color.
Graph coloring problem can also be solved using a state space tree, whereby
applying a backtracking method required results are obtained.
For solving the graph coloring problem, we suppose that the graph is
represented by its adjacency matrix G[ 1:n, 1:n], where, G[ i, j]= 1 if (i, j) is an
edge of G, and G[i, j] = 0 otherwise.
The colors are represented by the integers 1, 2, ..., m and the solutions are given
by the n-tuple (x1, x2, x3, ..., xn), where x1 is the color of node i.
This algorithm uses the recursive backtracking schema. In this algorithm colors
to be assigned are to determine from the range (0, m), i.e., m colors are
available.
C/C++
return true;
}
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
What is a chatbot?
Both types of chatbots aim to create a more personalized content experience for the
users, whether that's while watching a video, reading articles or buying new shoes.
These Chatbots hold the promise of being the next generation of technology that
people use to interact online with business enterprises. These Chatbots offer a lot of
advantages, one of which is that, because Chatbots communicate using a natural
language, users don't need to learn yet another new website interface, to get
comfortable with the unavoidable quirks.
Chatbots are capable to interpret human speech, and decide which information is
being sought. Artificial intelligence is getting smarter each day, and brands that are
integrating Chatbots with the artificial intelligence, can deliver one-to-one
individualized experiences to consumers.
Why chatbot?
Chatbots are easy to use and many customers prefer them over calling a
representative on the phone because it tends to be faster and less invasive. They can
also save money for companies and are easy to set up.
Chatbots are relatively new and most companies haven’t implemented them yet, it’s
only natural that users are interested in them. Hence, people want to discover what
chatbots can and cannot do.
The number of businesses using chatbots has grown exponentially. Chatbots have
increased from 30,000 in 2016 to over 100,000 today. Every major company has
announced their own chatbot and 60% of the youth population uses them daily.
These statistics prove that chatbots are the new-gen tech. No more waiting for the
right time to incorporate them into your business. The time is now. By the year 2020,
nearly 80% of businesses will have their own chatbot.
Billions of people are already using chatbots, so it’s time your business did too.
Benefits of chatbot?
Chatbots are being made to ease the pain that the industries are facing today. The
purpose of chat bots is to support and scale business teams in their relations with
customers.
Chatbots may sound like a futuristic notion, but according to Global Web Index
statistics, it is said that 75% of internet users are adopting one or more messenger
platforms. Although research shows us that each user makes use of an average of 24
apps a month, wherein 80% of the time would be in just 5 apps. This means you can
hardly shoot ahead with an app, but you still have high chances to integrate your
chatbot with one of these platforms.
1. Available 24*7:
I’m sure most of you have experienced listening to the boring music playing while
you’re kept on hold by a customer care agent. On an average people spend 7 minutes
until they are assigned to an agent. Gone are the days of waiting for the next available
operative. Bots are replacing live chat and other forms of contact such as emails and
phone calls.
Since chat bots are basically virtual robots they never get tired and continue to obey
your command. They will continue to operate every day throughout the year without
requiring to take a break. This improves your customer satisfaction and helps you
rank highly in your sector.
2. Handling Customers:
We humans are restricted to the number of things we can do at the same time. A
study suggests that humans can only concentrate on 3–4 things at the same time. If
it goes beyond that you are bound to meet errors.
Chatbots on the other hand can simultaneously have conversations with thousands
of people. No matter what time of the day it is or how many people are contacting
you, every single one of them will be answered instantly. Companies like Taco Bell
and Domino’s are already using chatbots to arrange delivery of parcels.
If you are a business owner you are bound have a lot of employees who need to be
paid for the work they do. And these expenses just keep adding up as business grows.
Chatbots are a one time investment which helps businesses reduce down on staff
required.
You could integrate a customer support chatbot in your business to cater to simple
queries of customers and pass on only the complex queries to customer support
agents.
Humans react to others based on their mood and emotions. If a agent is having a
good attitude or is in good mood he will most probably talk to customers in a good
way. In contrary to this the customer will not be satisfied.
Whereas chatbots are bound by some rules and obey them as long as they’re
programmed to. They always treat a customer in the most polite and perfect way no
matter how rough the person is. Also, in the travel and hospitality industry where
travelers do not speak the same language, a bot can be trained to communicate in the
language of the traveler.
Also, now there are numerous slack bots which automate repetitive tasks. This helps
people save time and increase productivity. For example, there are new items bought
from your eCommerce site or there is a bug reported then it sends a short summary
to a slack channel.
6. Personal Assistant:
People could use Bots as a fashion advisor for clothing recommendations, or ask
trading tips from a finance bot, suggest places to visit from a travel bot and so forth.
This would help the users get a more personal touch from the chatbot. Also, the
chatbot will remember all your choices and provide you with relevant choices the
next time you visit it.
Below we have compiled reasons why chatbots are important for your business and
how can they help in increasing revenues:
Most businesses these days have a web presence. But with being on the
internet, boundaries of day and night, availability and unavailability have
changed, so have user expectations. This is probably the biggest reason to use
them. Bots give the user an interactive experience. It makes customers feel
they are working with someone to help resolve their issue. If done right, bots
can help customers find what they are looking for and make them more likely
to return.
Customer Engagement
Along with a web presence, it has also become increasingly important for
brands to have a mobile presence - mobile apps, mobile-optimized websites.
Considering how chat has been around on the mobile for ages, most chatbot
implementations don’t need you to work on tweaking their UI, they are ready
to implement and so available to your customers immediately
You might argue that you have an app for that. Having an app for your brand
is great, but having users discover that app, download it and use it to stay
engaged is not an easy deal. Instead, implementing a chatbot - which works
on the mobile browser or a messaging-app which the user regularly uses -
makes it all the more reason for a customer to be engaged with the brand
Sell Intelligently
The best part about bots is they are cheap. Chatbot provide the necessary
infrastructure and APIs for creating these bots. They require minimal
maintenance and since it is automated, there is no labor-intensive work that
goes in there.
e. Customer Service
Track Order : Keep users up to date with order status. Schedule or reschedule
delivery to a provided address or request to pick it up at any other Best Buy
outlet.
Stock outs : Notify users when desired product is available and place order
over a chat.
Returns and Replacements : No waiting time to reach customer care.
Customers can instantly place request to replace or return an order.
Seek Reviews : Reach out to users to seek reviews on the products recently
bought
Gift Recommendations
Recommend relevant gifting options to users, accessing calendar events and
understanding the likes and style of beneficiary.
Opportunity to upsell gift cards for the users for every occasion.
Famous restaurant chains like Burger King and Taco bell has introduced their
Chatbots to stand out of competitors of the Industry as well as treat their customers
quickly. Customers of these restaurants are greeted by the resident Chatbots, and are
offered the menu options- like a counter order, the Buyer chooses their pickup
location, pays, and gets told when they can head over to grab their food. Chatbots
also works to accept table reservations, take special requests and go take the extra
step to make the evening special for your guests.
Chatbots are not only good for the restaurant staff in reducing work and pain but can
provide a better user experience for the customers.
For hoteliers, automation has been held up as a solution for all difficulties related to
productivity issues, labour costs, a way to ensure consistently, streamlined
production processes across the system. Accurate and immediate delivery of
information to customers is a major factor in running a successful online Business,
especially in the price sensitive and competitive Travel and Hospitality industry.
Chatbots particularly have gotten a lot of attention from the hospitality industry in
recent months.
Chatbots can help hotels in a number of areas, including time management, guest
services and cost reduction. They can assist guests with elementary questions and
requests. Thus, freeing up hotel staff to devote more of their time and attention to
time-sensitive, critical, and complicated tasks. They are often more cost effective
and faster than their human counterparts. They can be programmed to speak to guests
in different languages, making it easier for the guests to speak in their local language
to communicate.
Chatbots are a much better fit for patient engagement than Standalone apps. Through
these Health-Bots, users can ask health related questions and receive immediate
responses. These responses are either original or based on responses to similar
questions in the database. The impersonal nature of a bot could act as a benefit in
certain situations, where an actual Doctor is not needed.
Chatbots ease the access to healthcare and industry has favourable chances to serve
their customers with personalised health tips. It can be a good example of the success
of Chatbots and Service Industry combo.
Chatbots in E-Commerce
Mobile messengers- connected with Chatbots and the E-commerce business can
open a new channel for selling the products online. E-commerce Shopping
destination “Spring” was the early adopter. E-commerce future is where brands have
their own Chatbots which can interact with their customers through their apps.
Chat based health and fitness companies using Chatbot, to help their customers get
personalised health and fitness tips. Tech based fitness companies can have a huge
opportunity by developing their own Chatbots offering huge customer base with
personalised services. Engage with your fans like never before with news, highlights,
game-day info, roster and more.
Chatbots and Service Industry together have a wide range of opportunities and small
to big all size of companies using chatbots to reduce their work and help their
customers better.
Chatbots in Media
Big publisher or small agency, our suite of tools can help your audience chatbot
experience rich and frictionless. Famous News and Media companies like The Wall
Street Journal, CNN, Fox news, etc have launched their bots to help you receive the
latest news on the go.
Chatbot in Celebrity:
With a chatbot you can now have one-on-one conversation with millions of fans.
Chatbot in Marketing
SMS Marketing
Why promote just a coupon code that the customer does not know how to
use?
Improve conversions from your existing SMS campaigns.
Talk to your customers when they want to using “Talk to an Agent” feature.
Email Marketing
So your eMail has made a solid elevator pitch about your product.
As a next step, is making customers fill an online form the most exciting way
to engage with your customers?
It’s time to rethink the landing page.
Instantly engage in a conversation with your customers.
Address their concerns and queries
How effectively are you addressing the negative sentiment around your brand
on social media?
Addressing queries instantly and effectively can convert even an angry
customer into a loyal fan.
Leverage a chatbot as your first response strategy and comfort that customer.
Process
To run this project, you must have installed Python on your PC. After downloading the
project, follow the steps below:
Step1: Extract/Unzip the file
Step2: Go inside the project folder, open cmd then type bot.py and enter to start the system.
OR
Step2: Simply, double-click the bot.py file and you are ready to go.
Group-C
The expert system is a part of AI, and the first ES was developed in the year 1970, which was
the first successful approach of artificial intelligence. It solves the most complex issue as an
expert by extracting the knowledge stored in its knowledge base. The system helps in decision
making for compsex problems using both facts and heuristics like a human expert. It is
called so because it contains the expert knowledge of a specific domain and can solve any
complex problem of that particular domain. These systems are designed for a specific domain,
such as medicine, science, etc.
The performance of an expert system is based on the expert's knowledge stored in its
knowledge base. The more knowledge stored in the KB, the more that system improves its
performance. One of the common examples of an ES is a suggestion of spelling errors while
typing in the Google search box.
Below is the block diagram that represents the working of an expert system:
Below are some popular examples of the Expert System:
o High Performance: The expert system provides high performance for solving any type of
complex problem of a specific domain with high efficiency and accuracy.
o Understandable: It responds in a way that can be easily understandable by the user. It can take
input in human language and provides the output in the same way.
o Reliable: It is much reliable for generating an efficient and accurate output.
o Highly responsive: ES provides the result for any complex query within a very short period of
time.