Vishal Ai

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

200160107129

A Laboratory Manual for

Artificial Intelligence
(3170716)

B.E. Semester 7
(Computer Engineering)

Directorate of Technical Education, Gandhinagar,


Gujarat

Government Engineering College, Modasa


200160107129

CERTIFICATE

This is to certify that Mr. VAISHNAV VISHAL DIPAKBHAI Enrollment No.


200160107129 of B.E. Semester 7 Computer Engineering Department of this
Institute (GTU Code: 017) has satisfactorily completed the Practical / Tutorial work
for the subject Artificial Intelligence (3170716) for the academic year 2023-24.

Date:

Sign of Faculty Coordinator Head of Department


200160107129

Program Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life-long learning in the broadest context of technological change.
200160107129
Program Specific Outcomes (PSOs)

▪ Sound knowledge of fundamentals of computer science and engineering including software


and hardware.
▪ Develop the software using sound software engineering principles having web based/mobile
based interface.
▪ Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine learning.

Program Educational Objectives (PEOs)

▪ Possess technical competence in solving real life problems related to Computing.


▪ Acquire good analysis, design, development, implementation and testing skills to formulate
simple computing solutions to the business and societal needs.
▪ Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
▪ Embrace life-long learning and remain continuously employable.
▪ Work and excel in a highly competence supportive, multicultural and professional
environment which abiding to the legal and ethical responsibilities.
Artificial Intelligence (3170716) 200160107129

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant competencies
in psychomotor domain. By keeping in view, GTU has designed competency focused outcome-
based curriculum for engineering degree programs where sufficient weightage is given topractical
work. It shows importance of enhancement of skills amongst the students and it pays attention to
utilize every second of time allotted for practical amongst students, instructors and faculty
members to achieve relevant outcomes by performing the experiments rather than havingmerely
study type experiments. It is must for effective implementation of competency focused outcome-
based curriculum that every practical is keenly designed to serve as a tool to develop and enhance
relevant competency required by the various industry among every student. These psychomotor
skills are very difficult to develop through traditional chalk and board content delivery method in
the classroom. Accordingly, this lab manual is designed to focus on the industry defined relevant
outcomes, rather than old practice of conducting practical to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each experiment
in this manual begins with competency, industry relevant skills, course outcomes as well as
practical outcomes (objectives). The students will also achieve safety and necessary precautions
to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab activities
through each experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Artificial Intelligence (AI) has become an integral part of many industries and fields, impacting
human life in numerous ways. AI techniques, such as Predicate Logic, Production Rules, and
Semantic Networks, are used to encode knowledge in computer systems and solve real-world
problems. Additionally, fields of AI like Game Playing, Natural Language Processing, and
Connectionist Models play a vital role in various industries. It is essential for students to learn
programming languages for AI as it is used in both technical and non-technical fields. AI has been
implemented in every branch of engineering, making systems more effective and dynamic. The
Fundamentals of Artificial Intelligence course aims to provide exposure to the basic AI
techniques.

Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal of
errors if any.
Artificial Intelligence (3170716) 200160107129

Practical – Course Outcome matrix

Course Outcomes (COs):


CO-1 Understand the search technique procedures applied to real world problems
CO-2 Understand and use various types of logic and knowledge representation schemes.
CO-3 Understand various Game Playing techniques and apply them in programs.
CO-4 Gain knowledge in AI Applications and advances in Artificial Intelligence
CO-5 Use Prolog Programming language using predicate logic
Sr. CO
Objective(s) of Experiment CO1 CO3 CO4 CO5
No. 2
Write a Prolog program which contains three
predicates: male, female, parent. Make rules

1. for following family relations: father, mother, √
grandfather, grandmother, brother, sister,
uncle, aunt, nephew and niece.
Write a Prolog program to implement Water √
2. √
Jug Problem.
Solve 8 Puzzle Problem using A*Algorithm in any
3. √
programming Language.
Convert the given Prolog predicates into
Semantic Net.
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
4. caught(tom,bird1). √
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Artificial Intelligence (3170716) 200160107129

Construct the Conceptual Dependency for the


given statements.
5. √
1) John gives Mary a book
2) John gave Mary the book yesterday.
Implement the Minimax algorithm for a simple tic-
6. √
tac-toe game using Python Language.
Implement Bayesian Networks algorithm
7. for the Monty Hall Problem using any √
programming Language.
8. Demonstrate Connectionist Model using Tool. √
Implement Genetic Algorithm using any
9. √
programming Language.
Write a PROLOG program based on list:
1) To find the length of a list.
2) To sum all numbers of list.
3) To find whether given element is a member
of a list.
4) To append the list.

10. 5) To reverse the list. √


6) To find the last element of a list.
7) To delete the first occurrence of an element
from a list.
8) To delete every occurrence of an element from
a list.
9) To find Nth element from the list.
Artificial Intelligence (3170716) 200160107129

Guidelines for Faculty members

1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the students
and ensure that the respective skills and competencies are developed in the students
after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students

1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
2. Students will have to perform experiments as per practical list given.
3. Students have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

Common Safety Instructions

Students are expected to


1) switch on the PC carefully (not to use wet hands)
2) shutdown the PC properly at the end of your Lab
3) carefully handle the peripherals (Mouse, Keyboard, Network cable etc).
4) use Laptop in lab after getting permission from Teacher
Artificial Intelligence (3170716) 200160107129

Index
(Progressive Assessment Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar


No. No. perfor submiss nt Teacher ks
mance ion Marks with
date
Write a Prolog program which contains
three predicates: male, female, parent.
Make rules for following family relations:
1.
father, mother, grandfather, grandmother,
brother, sister, uncle, aunt, nephew and
niece.
Write a Prolog program to implement
2.
Water Jug Problem.
Solve 8 Puzzle Problem using A* Algorithm in
3.
any programming Language.
Convert the given Prolog predicates
into Semantic Net.
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
4. caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Construct the Conceptual Dependency for
the given statements.
5.
1) John gives Mary a book
2) John gave Mary the book yesterday.
Implement the Minimax algorithm for a simple
6.
tic-tac-toe game using Python Language.
Implement Bayesian Networks
7. algorithm for the Monty Hall Problem
using any programming Language.
Demonstrate Connectionist Model using
8.
Tool.
Artificial Intelligence (3170716) 200160107129

Implement Genetic Algorithm using


9.
any programming Language.
Write a PROLOG program based on list:
1) To find the length of a list.
2) To sum all numbers of list.
3) To find whether given element is a
member of a list.
4) To append the list.
10. 5) To reverse the list.
6) To find the last element of a list.
7) To delete the first occurrence of an
element from a list.
8) To delete every occurrence of an element
from a list.
9) To find Nth element from the list.
Total
200160107129

Experiment No: 1

Write a PROLOG program which contains three predicates: male, female,


parent. Make rules for following family relations: father, mother,
grandfather, grandmother, brother, sister, uncle, aunt, nephew and niece.

Date :

Competency and Practical Skills: Basic Understanding of Predicated and Prolog Syntax

Relevant CO: CO2, CO5

Objectives: To learn different kinds of knowledge bases of Prolog Programming.


To create a powerful and flexible system for representing, manipulating,
and reasoning about information in a logical and structured way.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

Theory:
There are only three basic constructs in Prolog: facts, rules, and queries. A collection of facts and
rules is called a knowledge base (or a database) and Prolog programming is all about writing
knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and
rules which describe some collection of relationships that we find interesting.

Knowledge Base 1
Knowledge Base 1 (KB1) is simply a collection of facts. Facts are used to state things that are
unconditionally true of some situation of interest. For example, we can state that Mia, Jody, and
Yolanda are women, that Jody plays air guitar, and that a party is taking place, using the following
five facts:

woman(mia).
woman (jody).
woman (yolanda).
playsAirGuitar(jody).
party.

We can ask Prolog whether Mia is a woman by posing the query:

?- woman (mia).
Prolog will answer
yes

1
200160107129
Knowledge Base 2
happy (yolanda).
listens 2Music(mia).
listens 2Music(yolanda): - happy (yolanda). playsAirGuitar(mia):- listens2Music(mia).
playsAirGuitar(yolanda):- listens 2Music(yolanda).

There are two facts in KB2, listens2Music(mia) and happy(yolanda). The last three items it contains
are rules.
Rules state information that is conditionally true of the situation of interest The part on the left hand
side of the: - is called the head of the rule, the part on the right hand side is called the body. So in
general rules say: if the body of the rule is true, then the head of the rule is true too. And now for
the key point:
If a knowledge base contains a rule head - body, and Prolog knows that body follows from the
information in the knowledge base, then Prolog can infer head. This fundamental deduction step is
called modus ponens.

Knowledge Base 3
KB3, our third knowledge base, consists of five clauses:
happy(vincent).
listens2Music (butch). playsAirGuitar (vincent):-
listens 2Music(vincent),
happy(vincent). playsAirGuitar(butch):-
happy(butch).
playsAirGuitar(butch):-
listens2Music(butch). There are two facts, happy(vincent) and listens2Music(butch), and three
rules.
KB3 defines the same three predicates as KB2 (namely happy, listens2Music, and playsAirGuitar)
but it defines them differently. In particular, the three rules that define the playsAirGuitar predicate
introduce some new ideas.

Knowledge Base 4
Here is KB4, our fourth knowledge base:
woman(mia).
woman(jody).
woman (yolanda).
loves (vincent,mia).
loves (marsellus,mia).
loves (pumpkin, honey_bunny).
loves (honey_bunny, pumpkin).

There are no rules, only a collection of facts. we're going to make use of variables. Here's an
example:
?- woman(X).

Prolog answers this query by working its way through KB4, from top to bottom, trying to unify (ormatch) the
expression woman(X) with the information KB4 contains. Now the first item in the knowledge base is woman(mia).
So, Prolog unifies X with mia, thus making the query agree
2
200160107129

perfectly with this first item.Prolog then reports back to us as follows:


X = mia
That is, it not only says that there is information about at least one woman in KB4, it actually tells
us who she is. It didn't just say yes, it actually gave us the variable binding (or variable instantiation)
that led to success.

Knowledge Base 5
person(john).
person(susan).
person(bob).
person(alice).

city(new_york).
city(london).
city(paris).
city(tokyo).

lives_in(john, new_york).
lives_in(susan, london).
lives_in(bob, paris).
lives_in(alice, tokyo).

likes(john, sushi).
likes(john, pizza).
likes(susan, pizza).
likes(bob, croissants).
likes(alice, sushi).

likes_same_food(X, Y) :-
likes(X, Z),
likes(Y, Z),
X \= Y.
In this example, we have defined a knowledge base that includes facts about people and cities, as
well as rules that define relationships between them. Specifically, we have defined the following:
• Four facts that define the people in our knowledge base (john, susan, bob, and alice) and the
cities they live in (new_york, london, paris, and tokyo).
• Five facts that define the food preferences of our people.
• A rule called likes_same_food/2 that defines a relationship between two people who like the
same food.
To use this knowledge base, we can query it using Prolog's built-in ?- operator. For example, we
can ask:
?- likes(john, sushi).
true.
This will return true, indicating that John likes sushi.

3
200160107129

Safety and necessary Precautions:


Use appropriate names and arguments for the predicates.
Make sure that the rules are accurate and cover all possible cases.

Procedure:
1. Define the domain of the knowledge base.
2. Define the facts.
3. Define the rules.
4. Test the knowledge base.

Observation/Program:
Code:
male(laxman).
male(dilip).
male(kantibhai).
male(dev).
male(jay).
female(naina).
female(manishaben).
female(sharadaben).
female(shreya).
parent(bharat,dev).
parent(bharat,shreya).
parent(naina,shreya).
parent(naina,dev).
parent(kantibhai,bharat).
parent(kantibhai,dilip).
parent(sharadaben,dilip).
parent(sharadaben,bharat).
parent(dilip,jay).
parent(manishaben,jay).

father(X,Y):-parent(X,Y),male(X).
mother(X,Y):-parent(X,Y),female(X).
grandfather(X,Z):-male(X),parent(X,Y),parent(Y,Z).
grandmother(X,Z):-parent(X,Y),father(Y,Z),female(X).
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
niece(X,Y):-female(X),brother(Z,Y),father(Z,X).
uncle(X,Y):-male(X),father(Z,Y),brother(X,Z).
aunt(X,Y):-female(X),father(K,Y),nephew(W,K),mother(X,W).

4
200160107129

Output:

Conclusion:
Prolog is a useful tool for implementing knowledge bases for various domains, including family
relationships, and can provide efficient and effective reasoning capabilities for querying and
analyzing such data.)

Quiz:(Sufficient space to be provided for the answers)


1. What is Prolog and what is it used for?
→ Prolog is a declarative programming language commonly used for artificial intelligence and
symbolic reasoning tasks. It is used for tasks like knowledge representation, rule-based systems,
natural language processing, and solving logic-based problems. Prolog excels at symbolic
manipulation and pattern matching, making it suitable for expert systems and knowledge-based
applications.

2. What is a knowledge base in Prolog and how is it represented?


→ In Prolog, a knowledge base is a collection of facts and rules that represent information about
a domain. It's typically represented using predicates and clauses. Facts are statements about
specific data, while rules define relationships and logic. Together, they form the knowledge that
Prolog can query and reason with.

3. How do you define facts and rules in Prolog?


→ In Prolog:
- Facts are defined by stating relationships between objects using predicates.
- Rules are defined using predicates and logical conditions, allowing for complex
relation-
ships and inference based on the given facts

4. What are the different types of knowledge bases in Prolog and how are they
implemented?
→ In Prolog, there are primarily two types of knowledge bases:
1. Static Knowledge Bases: These are implemented using facts and rules defined in the
source code. They do not change during program execution.
2. Dynamic Knowledge Bases: These are implemented using assert and retract predicates,
allowing facts and rules to be added or removed at runtime, making the knowledge base
dynamic.

5
200160107129

5. How do you query a Prolog knowledge base and what is the output?
→ To query a Prolog knowledge base, you use a query statement, often in the form of a
predicate. Prolog searches for solutions based on the defined facts and rules and provides all
possible solutions or "bindings" that satisfy the query. The output is a list of bindings that make
the query true, or it may return "false" if no solutions are found.

6. What are the advantages and disadvantages of using Prolog for implementing
knowledge bases?
→ Advantages:
- Declarative and easy-to-read syntax.
- Natural for expressing logical relationships.
- Suitable for symbolic AI and rule-based systems.
Disadvantages:
- Inefficient for certain tasks like numeric computation.
- Limited support for complex data structures.
- Steeper learning curve for those unfamiliar with logic programming.

7. What are some real-world applications of Prolog-based knowledge bases?


→ Real-World Applications are:
- Database query languages.
- Robotics and intelligent systems.
- Automated reasoning and theorem proving.
- Natural Language Processing.

Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online

References used by the students: (Sufficient space to be provided)


1. https://www.youtube.com/watch?v=GUF-RbTVgGo&t=529s

Rubric wise marks obtained:


Problem Completeness
Knowledge Logic
Rubric Recognition and accuracy Ethics (2)
(2) Building (2) Total
(2) (2)
s
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

6
200160107129

Experiment No: 2

Write a Prolog program to implement Water-Jug Problem.


Date:
Competency and Practical Skills: Knowledge of logic programming, Basics of search
Techniques

Relevant CO: CO1, CO5

Objectives: To create a functional and efficient Prolog program for solving logic puzzles.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

Theory:
The Water-Jug Problem is a classic problem in Artificial Intelligence that involves two jugs of
different sizes and the task of measuring a specific amount of water using these jugs. The problem
can be formulated as follows:
Given two jugs of sizes x and y, where x is greater than y, and an amount z of water to be measured,
the task is to find a sequence of steps to measure exactly z liters of water using only these two jugs.

To solve the problem using Breadth-First Search, we start with the initial state where both jugs are
empty and generate all possible next states from this state by applying the allowed actions such as
filling a jug and adding them to the queue until we find the desired goal state, which is when one of
the jugs contains exactly z liters of water. Once the goal state is reached, we backtrack to find the
sequence of steps taken to reach the goal state.

State Representation and Initial State – we will represent a state of the problem as a tuple (x, y)
where x represents the amount of water in the 4-gallon jug and y represents the amount of water in
the 3-gallon jug.
Note 0 ≤ x ≤ 4, and 0 ≤ y ≤ 3.
Our initial state: (0,0)
Goal Predicate – state = (2,y) where 0 ≤ y ≤ 3.

Operators –
• Fill the 4-gallon jug: This operator fills the 4-gallon jug to its maximum capacity. The
resulting state will be (4, y), where y is the amount of water in the 3-gallon jug.
• Fill the 3-gallon jug: This operator fills the 3-gallon jug to its maximum capacity. The
resulting state will be (x, 3), where x is the amount of water in the 4-gallon jug.
• Empty the 4-gallon jug: This operator empties the 4-gallon jug completely. The resulting
state will be (0, y), where y is the amount of water in the 3-gallon jug.
• Empty the 3-gallon jug: This operator empties the 3-gallon jug completely. The resulting
state will be (x, 0), where x is the amount of water in the 4-gallon jug.
• Pour water from the 4-gallon jug into the 3-gallon jug: This operator pours water from the
4-gallon jug into the 3-gallon jug until the 3-gallon jug is full or the 4-gallon jug is empty.
7
200160107129

• The resulting state will be (x - (3 - y), 3) if the 4-gallon jug becomes empty or (4, y) if the
3-gallon jug becomes full.
• Pour water from the 3-gallon jug into the 4-gallon jug: This operator pours water from the
3-gallon jug into the 4-gallon jug until the 4-gallon jug is full or the 3-gallon jug is empty.
The resulting state will be (4, y - (4 - x)) if the 3-gallon jug becomes empty or (x, 3) if the
4-gallon jug becomes full.

Safety and necessary Precautions:


It is important to handle edge cases such as unsolvable puzzles, invalid puzzle states, and memory
limitations to avoid program crashes or incorrect results.

Procedure:
1. Define the initial state using a Prolog predicate.
2. Define the goal state predicate.
3. Define the goal state predicate.
4. Define the operators
5. Define the search algorithm.

Observation/Program:
Code:
water_jug(X,Y):-X>4,Y<3, write('4L water jug overflowed.'),nl.
water_jug(X,Y):-X<4,Y>3, write('3L water jug is overflowed.'),nl.
water_jug(X,Y):-X>4,Y>3, write('Both water jugs overflowed.'),nl.

water_jug(X,Y):- (X=:=0,Y=:=0,nl,write('4L:0 & 3L:3 (Action: Fill 3L jug.)'),YY is


3,water_jug(X,YY));
(X=:=0,Y=:=0,nl,write('4L:4 & 3L:0 (Action: Fill 4L jug.)'),XX is 4,water_jug(XX,Y));
(X=:=2,Y=:=0,nl,write('4L:2 & 3L:0 (Action: Goal State Reached ... )'));
(X=:=4,Y=:=0,nl,write('4L:1 & 3L:3 (Action: Pour water from 4L to 3L jug.)'),XX is X-
3,YY is 3,water_jug(XX,YY));
(X=:=0,Y=:=3,nl,write('4L:3 & 3L:0 (Action: Pour water from 3L jug to 4L jug.)'),XX
is 3, YY is 0,water_jug(XX,YY));
(X=:=1,Y=:=3,nl,write('4L:1 & 3L:0 (Action: Empty 3L jug.)'),YY is
0,water_jug(X,YY));
(X=:=3,Y=:=0,nl,write('4L:3 & 3L:3 (Action: Fill 3L jug.)'),YY is 3,water_jug(X,YY));
(X=:=3,Y=:=3,nl,write('4L:4 & 3L:2 (Action: Pour water from 3L jug to 4L jug until 4L
jug is full.)'),XX is X+1,YY is Y-1,water_jug(XX,YY));
(X=:=1,Y=:=0,nl,write('4L:0 & 3L:1 (Action: Pour water from 4L to 3L jug.)'),XX is
Y,YY is X,water_jug(XX,YY));
(X=:=0,Y=:=1,nl,write('41:4 & 3L:1 (Action: Fill 4L jug.)'),XX is 4,water_jug(XX,Y));
(X=:=4,Y=:=1,nl,write('4L:2 & 3L:3 (Action: Pour water from 4L jug to 3L jug until 31
jug is full.)'),XX is X-2,YY is Y+2,water_jug(XX,YY));
(X=:=4,Y=:=2,nl,write('4L:0 & 31:2 (Action: Empty 4L jug.)'),XX is
0,water_jug(XX,Y));
(X=:=0,Y=:=2,nl,write('4L:2 & 3L:0 (Action: Pour water from 3L jug to 4L jug.)'),XX
is Y,YY is X,water_jug(XX,YY)).
8
200160107129

Output:

Conclusion:
The provided Prolog program demonstrates solving a Measuring Jugs Problem. It defines the initial
state, goal state, and transitions for pouring water between jugs. The goal is to measure out 2 liters
of water into one of the jugs without spilling any.

Quiz: (Sufficient space to be provided for the answers)


1. What search algorithm can you use to find a solution to the Water-Jug Problem, and
how would you implement it in Prolog?
→ To find a solution to the Water-Jug Problem in Prolog, you can use depth-first search (DFS)
as the search algorithm. DFS explores each branch of the search tree as deeply as possible before
backtracking. In the context of the Water-Jug Problem, each state represents a configuration of
the two jugs (the amount of water in each jug), and the search space is explored by applying the
three possible actions (filling a jug, emptying a jug, and pouring water between jugs) to
transition from one state to another until the goal state is reached.

2. How would you test the Prolog program to ensure that it works correctly?
→ When using SWI-Prolog, you can leverage its built-in debugging tools, including the
debugger and tracing capabilities, to test and debug your Prolog program for the Water-Jug
Problem effectively. These tools allow you to step through code execution, set breakpoints,
inspect variable values, and trace predicate calls, making it easier to identify and fix issues.

Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill

References used by the students: (Sufficient space to be provided)


1. https://youtu.be/GUF-RbTVgGo?si=WoA9TwCh8YQrnuGA

Rubric wise marks obtained:


Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

9
200160107129

Experiment No: 3

Solve 8 Puzzle Problem using A* Algorithm in any programming Language.


Date:
Competency and Practical Skills: Knowledge of logic programming

Relevant CO: CO1

Objectives: To optimize the performance of the A* algorithm by minimizing the number of states
explored and improving the efficiency of the heuristic function.

Equipment/Instruments: Personal Computer, open-source software for programming

Theory:

A* Algorithm
A* is a computer algorithm that is widely used in pathfinding and graph traversal, the process of
plotting an efficiently traversable path between multiple points, called nodes. Noted for its
performance and accuracy, it enjoys widespread use.

The key feature of the A* algorithm is that it keeps a track of each visited node which helps in
ignoring the nodes that are already visited, saving a huge amount of time. It also has a list that holds
all the nodes that are left to be explored and it chooses the most optimal node from this list, thus
saving time not exploring unnecessary or less optimal nodes.

So we use two lists namely ‘open list‘ and ‘closed list‘ the open list contains all the nodes that are
being generated and are not existing in the closed list and each node explored after it’s neighboring
nodes are discovered is put in the closed list and the neighbors are put in the open list this is how
the nodes expand. Each node has a pointer to its parent so that at any given point it can retrace the
path to the parent. Initially, the open list holds the start(Initial) node. The next node chosen from
the open list is based on its f score, the node with the least f score is picked up and explored.

f-score = h-score + g-score

A* uses a combination of heuristic value (h-score: how far the goal node is) as well as the g-score
(i.e. the number of nodes traversed from the start node to current node).

In our 8-Puzzle problem, we can define the h-score as the number of misplaced tiles by comparing
the current state and the goal state or summation of the Manhattan distance between misplaced
nodes.

g-score will remain as the number of nodes traversed from start node to get to the current node.

10
200160107129
calculate the h-score by comparing the initial(current) state and goal state and counting the number
of misplaced tiles.

Thus, h-score = 5 and g-score = 0 as the number of nodes traversed from the start node to the
current node is 0.

How A* solves the 8-Puzzle problem.

We first move the empty space in all the possible directions in the start state and calculate the f-
score for each state. This is called expanding the current state.

After expanding the current state, it is pushed into the closed list and the newly generated states
are pushed into the open list. A state with the least f-score is selected and expanded again. This
process continues until the goal state occurs as the current state. Basically, here we are providing
the algorithm a measure to choose its actions. The algorithm chooses the best possible action and
proceeds in that path.

This solves the issue of generating redundant child states, as the algorithm will expand the node
with the least f-score.

11
200160107129
Safety and necessary Precautions:
It is important to handle edge cases such as unsolvable puzzles, invalid puzzle states, and memory
limitations to avoid program crashes or incorrect results.

Procedure:
1. Define the starting and goal states of the puzzle.
2. Implement the A* algorithm, which uses the heuristic function to determine the best path to
reach the goal state.

Observation/Program:
Code:
class Node:
def init (self, data, level, fval):
self.data = data
self.level = level
self.fval = fval
def generate_child(self):
x, y = self.find(self.data, '_')
val_list = [[x, y - 1], [x, y + 1], [x - 1, y], [x + 1, y]]
children = []
for i in val_list:
child = self.shuffle(self.data, x, y, i[0], i[1])
if child is not None:
child_node = Node(child, self.level + 1, 0)
children.append(child_node)
return children
def shuffle(self, puz, x1, y1, x2, y2):
if x2 >= 0 and x2 < len(self.data) and y2 >= 0 and y2 < len(self.data):
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None
def copy(self, root):
temp = []
for i in root:
t = []
for j in i:
t.append(j)

temp.append(t)
return temp
def find(self, puz, x):
for i in range(0, len(self.data)):
for j in range(0, len(self.data)):
if puz[i][j] == x:
return i, j
class Puzzle:
12
200160107129
def init (self, size):
self.n = size
self.open = []
self.closed = []
def accept(self):
puz = []
for i in range(0, self.n):
temp = input().split(" ")
puz.append(temp)
return puz
def f(self, start, goal):
return self.h(start.data, goal) + start.level
def h(self, start, goal):
temp = 0
for i in range(0, self.n):
for j in range(0, self.n):
if start[i][j] != goal[i][j] and start[i][j] != '_':
temp += 1
return temp
def process(self):
print("\n Enter the initial state matrix below: \n")
start = self.accept()
print("\n Enter the goal state matrix below: \n")
goal = self.accept()
start = Node(start, 0, 0)
start.fval = self.f(start, goal)
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
print("")
print(" || ")
print("")
for i in cur.data:
for j in i:
print(j, end=" ")
print("")
if (self.h(cur.data, goal) == 0):
break
for i in cur.generate_child():
i.fval = self.f(i, goal)
self.open.append(i)
self.closed.append(cur)
del self.open[0]
self.open.sort(key=lambda x: x.fval, reverse=False)
puzle = Puzzle(3)
puzle.process()

13
200160107129
Output:

Conclusion:
The algorithm begins by adding the start state to the priority queue. At each step, the algorithm
removes the state with the lowest f-score from the queue and expands it, generating all of its possible
successor states. The successor states are then added to the priority queue, unless they have already
been visited. The algorithm terminates when the goal state is removed from the priority queue.

Quiz: (Sufficient space to be provided for the answers)

1. How do you generate successor states in the A* algorithm for solving the 8 Puzzle
Problem, and what information do you need to calculate their f-scores?
→ In the A* algorithm for solving the 8 Puzzle Problem (or any other problem), generating successor
states involves determining the possible moves from the current state and creating new states
accordingly. In the case of the 8 Puzzle Problem, you have a 3x3 grid with one empty tile, and you can

slide the adjacent tiles into the empty space. Each move results in a new state. To generate successor
states for the 8 Puzzle Problem: Identify the current state of the puzzle, which is represented as a 3x3
grid. Find the location of the empty tile (the tile with the value 0) in the grid. Determine the possible
moves (up, down, left, or right) based on the location of the empty tile. For example, if the empty tile is
in the middle of the grid, for the 8 Puzzle Problem include the Manhattan distance (sum of the horizontal
and vertical distances of each tile from its goal position) or the number of misplaced tiles. Add the
successor states, along with their f-scores, to the open list (priority queue or minheap) for further
exploration. The A* algorithm then selects the next state to explore from the open list based on the lowest
f-score, and the process continues until the goal state is reached or a solution is found.

14
200160107129
2. How does the A* algorithm decide which state to explore next in the search space, and
why is this decision important for the efficiency of the algorithm?

→ The A* algorithm decides which state to explore next in the search space based on a combination of
two values associated with each state: the cost to reach that state from the initial state (g-score) and an
estimated cost from that state to the goal state (h-score). The decision is made using a priority queue or
a min-heap, where states with lower f-scores (the sum of g-score and h-score) are given higher priority.
The key decision-making step in A* is as follows: For each state in the open list (the set of states to be
explored), calculate its f-score as f(n) = g(n) + h(n), where:
g(n): The cost of reaching the current state from the initial state (the actual cost incurred).
h(n): An estimate of the cost to reach the goal state from the current state (the heuristic estimate).
Select the state with the lowest f-score from the open list for expansion. This state becomes the current
state.
Expand the current state by generating its successor states and evaluating their f-scores. Add these
successor states to the open list.
Repeat steps 1 to 3 until one of the following conditions is met:
The g-score ensures that the algorithm explores states in the order of their actual cost, guaranteeing
optimality when the heuristic is admissible (i.e., it never overestimates the true cost).
The h-score guides the algorithm toward potentially promising states, allowing it to explore states
likely to lead to the goal more efficiently.

Suggested References:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill.

References used by the students: (Sufficient space to be provided)


1. https://saturncloud.io/blog/solving-the-8-puzzle-with-a-
algorithm/#:~:text=To%20solve%20the%208%20Puzzle%20using%20the%20A*%20algo
rithm%2C%20we,tile%20and%20its%20desired%20position.
Rubric wise marks obtained:

Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Masrks

15
200160107129

Experiment No: 4

Convert the given Prolog predicates into Semantic Net.


cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).

Date:

Competency and Practical Skills:Understanding of basics of semantic Net.

Relevant CO: CO2

Objectives:To Learn Basic symbols of Semantic Net.

Equipment/Instruments: Personal Computer, open-source software for programming

Theory:
Semantic Nets provide a powerful tool for representing and organizing knowledge in artificial
intelligence.

Semantic Nets use symbols to represent concepts and relationships between them. Here are the
common symbols used in Semantic Nets:

• Nodes or Concepts: Nodes represent concepts or objects in the Semantic Net. They are
usually represented by rectangles, circles or ovals. The name of the concept is usually
written inside the node.
• Arcs or Relations: Arcs represent the relationships between concepts in the Semantic Net.
They are usually represented by arrows or lines connecting two nodes. The label of the arc
describes the relationship between the two nodes.
• Attributes: Attributes are used to describe the properties or characteristics of a node or
concept. They are usually written inside the node as smaller labels.

16
200160107129
• Values: Values represent the specific values of attributes associated with a particular node
or concept. They are usually written next to the attribute label in the node.
• Unary Relations: Unary relations are used to represent a relationship between a concept and
an attribute. They are usually represented by an arrow pointing from the attribute to the
concept.
• Cardinality: Cardinality is used to indicate the number of objects that are related to a
particular concept. It is usually represented by a small number in a circle or next to the arc.
• Inheritance: Inheritance is used to represent the relationship between a general concept and
a more specific concept. It is usually represented by an arrow pointing from the specific
concept to the more general concept.

This representation consists of mainly two types of relations:


IS-A relation (Inheritance)
Kind-of-relation

Safety and necessary Precautions:

When creating a semantic net, it is important to avoid ambiguity by using clear and
concise notations. Ambiguity can lead to confusion and misinterpretation of the net.

Procedure:
1. Create a node for each object or concept.
2. Create an arc between each object and its attribute or property.
3. Add appropriate labels to each node and arc to indicate the relationship between objects.

Observation/Program:

17
200160107129
Conclusion:
In conclusion, we have created a node for each object or concept, created arc between each object
and its attribute or property. Added appropriate labels to each node and arc to indicate the
relationship between objects.
A semantic network, or frame network is a knowledge base that represents semantic relations
between concepts in a network. This is often used as a form of knowledge representation.

Quiz: (Sufficient space to be provided for the answers)


1. What is the advantage of using Semantic Nets for knowledge representation?
Semantic networks excel in visually representing knowledge, supporting natural language
processing, and enabling reasoning and inference. They offer a scalable, modular, and
human-understandable framework for knowledge representation, with applications in
diverse fields such as expert systems, search, and the Semantic Web.

2. What is the IS-A relation in a Semantic Net?


In a Semantic Network, the "IS-A" relation represents a type of hierarchical or taxonomic
relationship between two concepts or nodes. It signifies that one concept is a subclass or
subtype of another. For example, in a semantic network representing animals, "Lion IS-A
Mammal" means that a lion is a specific type of mammal. This hierarchical structure is
essential for organizing and classifying knowledge, allowing for inheritance of properties and
characteristics from broader categories to more specific ones

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)


https://www.techtarget.com/searchcontentmanagement/definition/semantic-network-knowledge-
graph

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

18
200160107129

Experiment No: 5

Construct the Conceptual Dependency for the given statements.


1) John gives Mary a book
2) John gave Mary the book yesterday.

Date:12/09/23

Competency and Practical Skills: Understanding of basics of Knowledge Representation.

Relevant CO: CO2

Objectives: To identify the agents involved


To identify the action performed
To identify the object of the action

Equipment/Instruments: Personal Computer, open-source software

Theory:
Conceptual Dependency originally developed to represent knowledge acquired from natural
language input.
The goals of this theory are:
• To help in the drawing of inference from sentences.
• To be independent of the words used in the original input.
• That is to say: For any 2 (or more) sentences that are identical in meaning there should be
only one representation of that meaning.
It has been used by many programs that portend to understand English (MARGIE, SAM, PAM).
CD developed by Schank et al. as were the previous examples.
CD provides:
• a structure into which nodes representing information can be placed
• a specific set of primitives
• at a given level of granularity.
Sentences are represented as a series of diagrams depicting actions using both abstract and real
physical situations.
• The agent and the objects are represented
• The actions are built up from a set of primitive acts which can be modified by tense.
Examples of Primitive Acts are:
ATRANS
-- Transfer of an abstract relationship. e.g. give.
PTRANS
-- Transfer of the physical location of an object. e.g. go.
PROPEL
-- Application of a physical force to an object. e.g. push.
MTRANS
-- Transfer of mental information. e.g. tell.
19
200160107129
INGEST
-- Actor ingesting an object. e.g. eat.
EXPEL
-- Actor getting rid of an object from body. e.g. ????.
Six primitive conceptual categories provide building blocks which are the set of allowable
dependencies in the concepts in a sentence:

PP
-- Real world objects.
ACT
-- Real world actions.
PA
-- Attributes of objects.
AA
-- Attributes of actions.
T
-- Times.
LOC
-- Locations.

• Arrows indicate the direction of dependency. Letters above indicate certain relationships:
o
-- object.
R
-- recipient-donor.
I

-- instrument e.g. eat with a spoon.


D
-- destination e.g. going home.

• Double arrows ( ) indicate two-way links between the actor (PP) and action (ACT).
• The actions are built from the set of primitive acts (see above).
o These can be modified by tense etc.
The use of tense and mood in describing events is extremely important and schank
introduced the following modifiers:
-- continuing
?
-- interrogative
/
-- negative
delta
-- timeless
c
-- conditional
the absence of any modifier implies the present tense.

20
200160107129

Advantages of CD:
• Using these primitives involves fewer inference rules.
• Many inference rules are already represented in CD structure.
• The holes in the initial structure help to focus on the points still to be established.

Disadvantages of CD:
• Knowledge must be decomposed into fairly low level primitives.
• Impossible or difficult to find correct set of primitives.
• A lot of inference may still be required.
• Representations can be complex even for relatively simple actions.

Safety and necessary Precautions:

• Primitive actions are the basic actions that can be performed or described without reference
to other actions or concepts.
Procedure:
1. Identify the main concepts and their relationships.
2. Use Proper Primitives to draw Conceptual Diagrams.

Observation/Program:

Conclusion:
Conceptual dependency is a powerful tool for representing the meaning of natural language
sentences in a language-independent and abstract way. Conceptual dependency representations can
be used for a variety of tasks, such as understanding the meaning of sentences, generating sentences,
answering questions, and making inferences.

21
200160107129
Quiz: (Sufficient space to be provided for the answers)

1. What is the purpose of a Conceptual Dependency diagram?


The purpose of a Conceptual Dependency (CD) diagram is to represent the meaning of a
sentence in a structured graphical format. It simplifies and abstracts the core concepts and
relationships within the sentence, aiding in semantic representation, natural language

understanding, and integration with knowledge representation systems for inference and
reasoning.
2. How can Conceptual Dependency be used in natural language processing?
Conceptual Dependency (CD) is employed in Natural Language Processing (NLP) to
bridge the gap between human language and machine understanding. CD diagrams break
down sentences into essential semantic components, facilitating tasks like information
retrieval, sentiment analysis, and machine translation. This abstraction aids in analyzing
and processing language, enabling more accurate and meaningful interactions between
humans and computers.
3. Can a Conceptual Dependency primitive be further decomposed?
Yes, Conceptual Dependency (CD) primitives can be further decomposed or expanded to
represent more detailed and specific information.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

22
200160107129

Experiment No: 6

Implement the Minimax algorithm for a simple tic-tac-toe game


using Python Language.

Date:26/09/23

Competency and Practical Skills:


Basic knowledge of Python programming language, Familiarity with the rules of tic-tac-toe game,
including the board layout and winning conditions.
Understanding of the Minimax algorithm, which is a decision-making algorithm.

Relevant CO: CO3

Objectives: To illustrate how to recursively apply the Minimax algorithm to build a game tree
and determine the optimal move for the computer player.

Equipment/Instruments: Personal Computer, Python3, Jupytor Notebook

Theory:
• The Minimax Algorithm is a popular decision-making algorithm used in game
theory, which allows a player to determine the best possible move to make, given
that the opponent will also make the best possible move.
• Here's a general implementation of the Minimax algorithm:
• Define the game state: The game state should be defined in terms of the current
state of the board or game, including the position of all pieces, scores, and any other
relevant information.
• Define the game tree: The game tree represents all the possible moves that can be
made from the current game state, and the resulting game states that will arise from
each move. The game tree can be constructed recursively, with the root node
representing the current game state, and the child nodes representing the possible
moves that can be made from that state.
• Assign scores to each game state: At the bottom of the game tree, assign a score to
each game state based on the outcome of the game from that state. For example, if
the game is won by the player who reached that state, assign a positive score, and
if the game is lost, assign a negative score.
• Determine the best move: Starting from the root node, alternate between selecting
the move that maximizes the score for the player and selecting the move that
minimizes the score for the opponent until you reach a leaf node. The score of that
leaf node will then be propagated back up the tree to the root node, and the best
move will be the one that leads to the highest score.

23
200160107129
Safety and necessary Precautions:

Handle edge cases such as invalid moves, repeated moves, and game-ending conditions to avoid
program crashes or incorrect results.

Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.

Observation/Program:

#Tic-Tac-Toe using Mini-Max Algorithm

#This function is used to draw the board's current state every time the user turn arrives.
def ConstBoard(board):
print("Current State Of Board : \n\n");
for i in range (0,9):
if((i>0) and (i%3)==0):
print("\n");
if(board[i]==0):
print("- ",end=" ");
if (board[i]==1):
print("O ",end=" ");
if(board[i]==-1):
print("X ",end=" ");
print("\n\n");

#This function takes the user move as input and make the required changes on the board.
def User1Turn(board):
pos=input("Enter X's position from [1...9]: ");
pos=int(pos);
if(board[pos-1]!=0):
print("Wrong Move!!!");
exit(0) ;
board[pos-1]=-1;

def User2Turn(board):
pos=input("Enter O's position from [1...9]: ");
pos=int(pos);
if(board[pos-1]!=0):
print("Wrong Move!!!");
exit(0);
board[pos-1]=1;

24
200160107129
#MinMax function.
def minimax(board,player):
x=analyzeboard(board);
if(x!=0):
return (x*player);
pos=-1;
value=-2;
for i in range(0,9):
if(board[i]==0):
board[i]=player;
score=-minimax(board,(player*-1));
if(score>value):
value=score;
pos=i;
board[i]=0;

if(pos==-1):
return 0;
return value;

#This function makes the computer's move using minmax algorithm.


def CompTurn(board):
pos=-1;
value=-2;
for i in range(0,9):
if(board[i]==0):
board[i]=1;
score=-minimax(board, -1);
board[i]=0;
if(score>value):
value=score;
pos=i;

board[pos]=1;

#This function is used to analyze a game.


def analyzeboard(board):
cb=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];

for i in range(0,8):
if(board[cb[i][0]] != 0 and
board[cb[i][0]] == board[cb[i][1]] and
board[cb[i][0]] == board[cb[i][2]]):
return board[cb[i][2]];
return 0;

25
200160107129

#Main Function.
def main():
choice=input("Enter 1 for single player, 2 for multiplayer: ");
choice=int(choice);
#The broad is considered in the form of a single dimentional array.
#One player moves 1 and other move -1.
board=[0,0,0,0,0,0,0,0,0];
if(choice==1):
print("Computer : O Vs. You : X");
player= input("Enter to play 1(st) or 2(nd) :");
player = int(player);
for i in range (0,9):
if(analyzeboard(board)!=0):
break;
if((i+player)%2==0):
CompTurn(board);
else:
ConstBoard(board);
User1Turn(board);
else:
for i in range (0,9):
if(analyzeboard(board)!=0):
break;
if((i)%2==0):
ConstBoard(board);
User1Turn(board);
else:
ConstBoard(board);
User2Turn(board);

x=analyzeboard(board);
if(x==0):
ConstBoard(board);
print("Draw!!!")
if(x==-1):
ConstBoard(board);
print("X Wins!!! Y Loose !!!")
if(x==1):
ConstBoard(board);
print("X Loose!!! O Wins !!!!")

# #
main()
# #

26
200160107129
Output:

27
200160107129
Conclusion:
In conclusion, the application of the Minimax algorithm in the context of the Tic Tac Toe game is
a powerful demonstration of how artificial intelligence can be used to create challenging and
strategic gameplay. This algorithm ensures that players, whether human or computer, make the best
possible moves by analyzing all possible outcomes and minimizing the chance of losing. Through
a recursive search of game states and the use of a scoring system, Minimax optimizes decision-
making. While Tic Tac Toe is a relatively simple game, the Minimax algorithm can be applied to
more complex games and scenarios, making it an essential tool in the world of AI and game
development.

Quiz: (Sufficient space to be provided for the answers)


1. How can you optimize the Minimax algorithm to improve its performance in Tic
Tac Toe?
To optimize Minimax in Tic Tac Toe: employ alpha-beta pruning for efficient search, use
transposition tables to store board positions, create a heuristic evaluation function for
quicker pruning, and apply iterative deepening to balance depth and time constraints,
improving performance.
2. Can the Minimax algorithm be used for games other than Tic Tac Toe? If so, what
are some examples?
Yes, the Minimax algorithm can be used for various two-player, zero-sum games with
perfect information. Examples include chess, checkers, Connect Four, Othello, and Go.
It's also applied in AI for decision-making in non-gaming scenarios, such as resource
allocation and optimization problems.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)


https://www.geeksforgeeks.org/finding-optimal-move-in-tic-tac-toe-using-minimax-algorithm-in-
game-theory/
https://github.com/vineetjoshi253/TicTacToe-MiniMax/blob/master/Tic-Tac-Toe.py

Rubric wise marks obtained:


Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

28
200160107129

Experiment No: 7

Implement Bayesian Networks algorithm for the Monty Hall Problem


using any programming Language.

Date:03/10/23

Competency and Practical Skills: Understanding of Bayesian Networks.


Familiarity with the Monty Hall problem, which is a classic probability puzzle that involves three
doors and a prize.
Knowledge of probability theory, including conditional probability and Bayes' theorem.
Familiarity with a programming language

Relevant CO: CO4

Objectives:To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.

Equipment/Instruments: Personal Computer, Programming Language

Theory:
Bayesian Networks is a probabilistic graphical model used for representing and reasoning about
uncertain knowledge. It consists of a directed acyclic graph (DAG) where nodes represent random
variables and edges represent dependencies between them. Each node has a conditional probability
distribution (CPD) that describes the probability of that node given its parents. Bayesian Networks
can be used for a wide range of tasks including prediction, classification, diagnosis, and decision-
making.
The algorithm for constructing a Bayesian Network involves the following steps:
• Identify the random variables: The first step is to identify the random variables that are
relevant to the problem. These variables can be discrete or continuous, and can represent
events, states, or properties.
• Define the dependencies: The next step is to define the dependencies between the variables.
This is done by specifying the causal relationships between the variables, and determining
which variables are parents and which are children.
• Assign probabilities: The next step is to assign probabilities to the variables. This involves
specifying the prior probabilities for each variable, as well as the conditional probabilities
for each node given its parents.
• Construct the graph: The final step is to construct the DAG by connecting the nodes
according to their dependencies, and specifying the CPDs for each node.

29
200160107129
The Monty Hall problem

It is a famous probability puzzle based on a game show scenario. The problem is named after Monty
Hall, the host of the game show "Let's Make a Deal".
The scenario goes as follows:
• There are three doors, behind one of which is a prize, and behind the other two are goats.
The player chooses one door, and then the host, who knows what is behind each door, opens
one of the other two doors to reveal a goat. The player is then given the option to switch
their choice to the other unopened door or stick with their original choice.
• The question is: should the player switch their choice, or stick with their original choice?
• The answer is that the player should always switch their choice.
• To understand why this is the case, consider the following:
• When the player initially chooses a door, there is a 1/3 chance that they have chosen the
door with the prize, and a 2/3 chance that they have chosen a door with a goat. When the
host then opens one of the other doors to reveal a goat, the probability that the player's initial
choice was correct remains at 1/3. However, the probability that the prize is behind the other
unopened door is now 2/3.
• Therefore, when given the option to switch, the player should always switch because the
probability of winning the prize increases from 1/3 to 2/3. This may seem counterintuitive,
as it goes against our initial intuition that the probability of winning should be equally
distributed among the three doors. However, this is a classic example of how probabilities
can be counterintuitive, and why it is important to understand the underlying mathematics.

• Safety and necessary Precautions:

Ensure that the algorithm produces accurate results, it is important to validate the input data
to ensure that it is consistent and complete.

Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.

Observation/Program:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

// Define constants for the number of doors and simulations


const int NUM_DOORS = 3;
const int NUM_SIMULATIONS = 100000;

30
200160107129

// Function to simulate the Monty Hall problem


bool simulateMontyHall() {
// Initialize doors with goats
std::vector<bool> doors(NUM_DOORS, false);

// Place a car behind a random door


int carPosition = std::rand() % NUM_DOORS;
doors[carPosition] = true;

// Contestant's initial choice


int initialChoice = std::rand() % NUM_DOORS;

// Monty Hall opens a door with a goat


int openDoor;
do {
openDoor = std::rand() % NUM_DOORS;
} while (openDoor == initialChoice || doors[openDoor]);

// Decide whether to switch or stick


int finalChoice;
do {
finalChoice = std::rand() % NUM_DOORS;
} while (finalChoice == initialChoice || finalChoice == openDoor);

// Return true if the final choice is the door with the car, false otherwise
return doors[finalChoice];
}
int main() {
std::srand(std::time(0));

int switchWins = 0;
int stayWins = 0;

for (int i = 0; i < NUM_SIMULATIONS; i++) {


if (simulateMontyHall()) {
switchWins++;
} else {
stayWins++;
}
}
std::cout << "With switching: " << static_cast<double>(switchWins) / NUM_SIMULATIONS
* 100 << "% win rate." << std::endl;
std::cout << "Without switching: " << static_cast<double>(stayWins) / NUM_SIMULATIONS
* 100 << "% win rate." << std::endl;

31
200160107129
return 0;
}

Conclusion:
In summary, the program is a practical way to illustrate the Monty Hall Problem and reinforces the
importance of using probability and logic to make decisions in situations involving uncertainty and
random chance. It serves as a useful teaching and learning tool for probability theory and decision-
making.
Quiz: (Sufficient space to be provided for the answers)

1. hat is inference in a Bayesian Network?


Inference in a Bayesian Network refers to the process of using known information to draw
conclusions or make predictions about unknown variables by applying probabilistic
reasoning based on the network's structure and conditional probabilities

2. What are some applications of Bayesian Networks?


Bayesian Networks find applications in fields like healthcare (diagnosis and prognosis),
finance (risk assessment), natural language processing (language modeling), and robotics
(perception and decision-making). They're valuable for modeling and reasoning under
uncertainty.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)

Rubric wise marks obtained:


Problem Logic Completeness
Knowledge
Recognition Building and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

32
200160107129

Experiment No: 8

Demonstrate Connectionist Model using Tool.

Date:10/10/23

Competency and Practical Skills:

Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.

Relevant CO: CO4

Objectives: Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.

Equipment/Instruments: Personal Computer, Connectionist Models Tool

Theory:

Connectionist Models

• In contrast to the symbolist architectures in which the mind is assumed to be a physical


symbol-processing system, connectionist systems are networks of large numbers of
interconnected “units.” Each unit can have associated with it a certain amount of
activation. Connections to other units are given explicit weights (including negative
weights).
• Activation spreads from one unit to another as a function of the weighted links. For
example, the function of a typical link might be to multiply the input activation by its
weight and then apply a threshold function. A typical unit would sum all of its input
activations, then divide this among all its links. The weights on the links are adjustable
with experience.
• Some of the links may represent sensory inputs from the outside world; some may
represent output to effectors to the outside world. Units in connectionist models are
usually taken to be below the level of a symbol. For example, different units may
represent visual features of a letter such as verticalness or roundedness.

Neural networks are by far the most commonly used connectionist model
today.

• Though there are a large variety of neural network models, they almost always follow two
basic principles regarding the mind:

33
200160107129
• Any mental state can be described as an (N)-dimensional vector of numeric activation values
over neural units in a network.
• Memory is created by modifying the strength of the connections between neural units. The
connection strengths, or "weights", are generally represented as an N×N matrix.

Some Examples of popular tools:


• TensorFlow: An open-source platform developed by Google for building and training
machine learning models, including neural networks. It provides a high-level API that makes
it easy to build complex models with multiple layers and customizable activation functions.
• PyTorch: An open-source machine learning library developed by Facebook that provides a
dynamic computational graph for building neural networks. It is highly optimized for GPU
acceleration and provides a Pythonic interface for building and training models.
• Keras: A high-level neural networks API developed in Python that can run on top of
TensorFlow, CNTK, or Theano. It provides a simple and intuitive interface for designing
and training neural networks, and supports both convolutional and recurrent networks.
• Caffe: A deep learning framework developed by Berkeley AI Research (BAIR) that is
optimized for speed and memory efficiency. It provides a C++ API for building and training
neural networks and supports a variety of pre-trained models for image recognition and other
tasks.
• FastAI: A Python library that provides tools for building and training deep learning models,
including neural networks, with a focus on ease of use and fast prototyping.

Safety and necessary Precautions:


Different tools are designed for different tasks, and it's crucial to use a tool that is
appropriate for the task at hand.
Procedure:
• Choose a connectionist modeling tool
• Define the problem
• Design the architecture of the
• Implement the model
• Test the model
• Deploy the model

34
200160107129

Observation/Program:

# Import necessary libraries


from keras.models import Sequential
from keras.layers import Dense
from keras.datasets import mnist
from keras.utils import to_categorical

# Load and preprocess the MNIST dataset


(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape((-1, 28*28)) / 255.0 # Flatten the 28x28 images and normalize the pixel
values
x_test = x_test.reshape((-1, 28*28)) / 255.0
y_train = to_categorical(y_train, 10) # One-hot encode the labels
y_test = to_categorical(y_test, 10)

# Build the neural network model


model = Sequential()
model.add(Dense(128, input_shape=(784,), activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax')) # Output layer with 10 units for 10 classes (digits 0 to
9)

# Compile the model


model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Train the model


model.fit(x_train, y_train, epochs=10, batch_size=128, validation_split=0.2)

# Evaluate the model on the test data


loss, accuracy = model.evaluate(x_test, y_test)
print(f'Test accuracy: {accuracy:.2f}')

Conclusion:

In this Python program, a neural network was constructed using Keras for classifying MNIST
handwritten digits. The dataset was preprocessed, including flattening and normalization. The
model, with hidden layers and softmax output, was trained and evaluated, achieving an accuracy of
approximately 98%. The code showcases fundamental concepts in deep learning.

35
200160107129
Quiz: (Sufficient space to be provided for the answers)

1. What is the role of the activation function in a connectionist model?


An activation function in a connectionist model determines the output of a neuron or node
based on its input, introducing non-linearity and enabling complex pattern recognition and
learning.

2. What is the purpose of testing a connectionist model?


Testing a connectionist model assesses its performance by evaluating how well it
generalizes to new data, ensuring its reliability and effectiveness for real-world applications.

3. What is back propagation in a connectionist model?


Backpropagation is an algorithm in a connectionist model used to adjust network weights
by propagating error information backward through the network, enabling supervised
learning and improving the model's accuracy.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)


1. Machine Learning with Python for Everyone, Mark Fenner, Pearson
2. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley

Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Rubric Recognition Building Ethics (2)
(2) (2) Total
s (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

36
200160107129

Experiment No: 9

Implement Genetic Algorithm in any Programming Language.

Date:17/10/23

Competency and Practical Skills:

Understanding of genetic algorithms, which are a class of optimization algorithms that are
inspired by the principles of natural selection and genetics.
Knowledge of a programming language

Relevant CO: CO4

Objectives: To use a computational approach that mimics the process of natural selection to
solve optimization problems

Equipment/Instruments: Programming language

Theory:

Genetic Algorithm (GA) is a popular meta heuristic optimization algorithm in the field of artificial
intelligence (AI).Genetic Algorithms are based on the theory of natural selection and work on
generating a set of random solutions and making them compete in an arena where only the fittest
survive. It is often used to solve complex optimization problems where other traditional methods
may not work well.

GA works by maintaining a population of candidate solutions (also called chromosomes) and


applies genetic operators such as selection, crossover, and mutation to create new and hopefully
better solutions. The basic idea is to mimic the natural process of evolution and survival of the fittest
in order to find the optimal solution to a problem.

The first step in using GA for an AI problem is to define the problem as an optimization problem.
This involves identifying the objective function that needs to be optimized and the constraints (if
any) that need to be satisfied.

Once the problem is defined, the next step is to create an initial population of candidate solutions.
The population is typically generated randomly or using some heuristics depending on the problem.

The fitness function is then defined, which evaluates each chromosome in the population based on
how well it satisfies the objective function and constraints.

Next, the GA applies selection, crossover, and mutation operators to create new and hopefully better

37
200160107129
solutions. Selection involves choosing the top-performing chromosomes to be carried over to the
next generation. Crossover involves combining two chromosomes to create new offspring. Mutation
involves randomly changing some genes in a chromosome to introduce diversity into the
population.

The GA then repeats the process of selection, crossover, and mutation for a number of generations
or until a stopping criterion is met (such as reaching a maximum number of generations or finding
an optimal solution).

Safety and necessary Precautions:

It is important to define clear objectives and constraints for the optimization problem.
It is crucial to validate the fitness function.

Procedure:
1. Define the problem
2. Define the representation
3. Initialize the population.
4. Evaluate the fitness
5. Select parents.
6. Create offspring: Use genetic operators such as crossover and mutation to create offspring
from the selected parents.
7. Evaluate the offspring.
8. Select survivor
9. Check stopping criteria

Observation/Program:

import random

def generate_population(size):
population = []
for _ in range(size):
genes = [0, 1]
chromosome = []
for _ in range(len(items)):
chromosome.append(random.choice(genes))
population.append(chromosome)
print("Generated a random population of size", size)
return population

def calculate_fitness(chromosome):
total_weight = 0
total_value = 0
for i in range(len(chromosome)):
if chromosome[i] == 1:
38
200160107129
total_weight += items[i][0]
total_value += items[i][1]
if total_weight > max_weight:
return 0
else:
return total_value

def select_chromosomes(population):
fitness_values = []
for chromosome in population:
fitness_values.append(calculate_fitness(chromosome))

fitness_values = [float(i)/sum(fitness_values) for i in fitness_values]

parent1 = random.choices(population, weights=fitness_values, k=1)[0]


parent2 = random.choices(population, weights=fitness_values, k=1)[0]

print("Selected two chromosomes for crossover")


return parent1, parent2

def crossover(parent1, parent2):


crossover_point = random.randint(0, len(items)-1)
child1 = parent1[0:crossover_point] + parent2[crossover_point:]
child2 = parent2[0:crossover_point] + parent1[crossover_point:]

print("Performed crossover between two chromosomes: ")


print(parent1," ",parent2)
return child1, child2

def mutate(chromosome):
mutation_point = random.randint(0, len(items)-1)
if chromosome[mutation_point] == 0:
chromosome[mutation_point] = 1
else:
chromosome[mutation_point] = 0
print("Performed mutation on a chromosome")
print(chromosome)
return chromosome

def get_best(population):
fitness_values = []
for chromosome in population:
fitness_values.append(calculate_fitness(chromosome))

max_value = max(fitness_values)
max_index = fitness_values.index(max_value)

39
200160107129
return population[max_index]

# items that can be put in the knapsack


items = [
[1, 2],
[2, 4],
[3, 4],
[4, 5],
[5, 7],
[6, 10]
]

# print available items


print("Available items:\n", items)

# parameters for genetic algorithm


max_weight = 10
population_size = 10
mutation_probability = 0.05
generations = 1

print("\nGenetic algorithm parameters:")


print("Max weight:", max_weight)
print("Population:", population_size)
print("Mutation probability:", mutation_probability)
print("Generations:", generations, "\n")
print("Performing genetic evolution:")

# generate a random population


population = generate_population(population_size)

# evolve the population for specified number of generations


for _ in range(generations):
# select two chromosomes for crossover
parent1, parent2 = select_chromosomes(population)

# perform crossover to generate two new chromosomes


child1, child2 = crossover(parent1, parent2)

# perform mutation on the two new chromosomes


if random.uniform(0, 1) < mutation_probability:
child1 = mutate(child1)
if random.uniform(0, 1) < mutation_probability:
child2 = mutate(child2)

# replace the old population with the new population

40
200160107129
population = [child1, child2] + population[2:]

# get the best chromosome from the population


best = get_best(population)

# get the weight and value of the best solution


total_weight = 0
total_value = 0
for i in range(len(best)):
if best[i] == 1:
print("\nSelected index: ", i)
total_weight += items[i][0]
total_value += items[i][1]

# print the best solution


print("\nThe best solution:")
print("Weight:", total_weight)
print("Value:", total_value)

Conclusion:

41
200160107129

Quiz: (Sufficient space to be provided for the answers)


1. What are the genetic operators that will be used to create new individuals in each
generation? Will you use crossover, mutation, or both?
Both crossover and mutation operators will be utilized to create new individuals in each
generation of the genetic algorithm. Crossover combines genetic information from two
parents, while mutation introduces small, random changes to individual genes.

2. How will you evaluate the fitness of each individual in the population? Will you
evaluate them sequentially or in parallel?
The method for evaluating the fitness of individuals in a population depends on the specific
problem and algorithm. Evaluation can be done sequentially or in parallel, depending on
computational resources and the nature of the fitness function.

3. What is the stopping criterion for the genetic algorithm? Will you stop when a certain
fitness level is reached, after a certain number of generations, or when the algorithm
converges?
The stopping criterion for a genetic algorithm can vary depending on the problem and
goals. Common criteria include reaching a certain fitness level, a predefined number of
generations, or when the algorithm converges, which can be determined by monitoring
fitness improvements or population stability.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)

https://plainenglish.io/blog/genetic-algorithm-in-python-101-da1687d3339b
Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

42
200160107129

Experiment No: 10

Write a PROLOG program based on List Operations.

• To find the length of a list.


• To sum all numbers of list.
• To find whether given element is a member of a list.
• To append the list.
• To reverse the list.
• To find the last element of a list.
• To delete the first occurrence of an element from a list.
• To delete every occurrence of an element from a list.
• To find nth element from the list.

Date:31/10/23

Competency and Practical Skills:

Knowledge of basic PROLOG syntax

Relevant CO: CO5

Objectives: Understand the basic data structure for lists


Learn basic list operations

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

Theory:

The list is a simple data structure that is widely used in non-numeric programming. List consists of
any number of items, for example, red, green, blue, white, dark. It will be represented as, [red, green,
blue, white, dark]. The list of elements will be enclosed with square brackets.

A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog atom,
[]. In the second case, the list consists of two things as given below –

The first item, called the head of the list;

The remaining part of the list, called the tail.

Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green,
blue, white, dark]. So the tail is another list.

Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write the
43
200160107129
list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.

So the following list representations are also valid −


[a, b, c] = [x | [b, c] ]
[a, b, c] = [a, b | [c] ]
[a, b, c] = [a, b, c | [ ] ]
For these properties we can define the list as –

A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has
to be a list.

Basic Operations on Lists


Following table contains various operations on prolog lists –

Operations Definition

Membership During this operation, we can verify whether a given element is member of
Checking specified list or not?

Length Calculation With this operation, we can find the length of a list.

Concatenation Concatenation is an operation which is used to join/add two lists.

Delete Items This operation removes the specified element from a list.

Append Items Append operation adds one list into another (as an item).

Insert Items This operation inserts a given item into a list.

Safety and necessary Precautions:

The program should handle exceptions, such as input errors or invalid operations.

Procedure:

1. Define the Structure of List in Prolog.


2. Perform Different List operations.

Observation/Program:

1. Length

% length of empty list is 0 (base case)


list_len([], 0).
list_len([_ | L], N) :-
44
200160107129
list_len(L, N1),
N is N1 + 1.
% If length of L is N1, then length of [_ | L] will be N1 + 1

2. Sum

list_sum([],0).

list_sum([Head|Tail], TotalSum):- list_sum(Tail, Sum1),


TotalSum is Head+Sum1.

3. Member

is_member(X, [X | _]) :- !. % If the head of the list is X

is_member(X, [_ | Rest]) :- % else recur for the rest of the list


is_member(X, Rest).

4. Append List

% If L1 is empty, resultant list will be equal to L2 (base case)


append_list([], L2, L2).

append_list([X | L1], L2, [X | L3]) :-


append_list(L1, L2, L3).

5. Reverse List

list_concat([],L,L).
list_concat([X1|L1],L2,[X1|L3]) :- list_concat(L1,L2,L3).

list_rev([],[]).
list_rev([Head|Tail],Reversed) :-

45
200160107129
list_rev(Tail, RevTail),list_concat(RevTail, [Head],Reversed).

6. Last Element

lastElement([Head]) :- write(Head).
lastElement([_|Tail]):-
lastElement(Tail).

7. Delete first occurrence

% Deletion of any element from empty list will produce empty list(base case)
delete_element(_, [], []).

delete_element(X, [X | L], L) :- !.

delete_element(X, [Y | L], [Y | L1]) :-


delete_element(X, L, L1).

8. Delete every occurrence

delete_all(_, [], []).


delete_all(X, [X|T], Result) :-
delete_all(X, T, Result).
delete_all(X, [H|T], [H|Result]) :-
X \= H,
delete_all(X, T, Result).

9. Find nth element

find([H|_],0,H) :-
!.
find([_|T],N,H) :-
N > 0, %add for loop prevention

46
200160107129
N1 is N-1,
find(T,N1,H).

Conclusion:

In conclusion, Prolog provides a powerful and expressive way to work with lists through its
recursive and pattern matching capabilities. Whether you're filtering data, searching for specific
elements, or transforming lists, Prolog offers a declarative and logical approach to solving a variety
of list-related problems.

Quiz: (Sufficient space to be provided for the answers)


1) What is a list in Prolog?

The list is a simple data structure that is widely used in non-numeric programming. List
consists of any number of items, for example, red, green, blue, white, dark. It will be
represented as, [red, green, blue, white, dark]. The list of elements will be enclosed with
square brackets.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/

References used by the students: (Sufficient space to be provided)

1. https://www.tutorialspoint.com/prolog/prolog_lists.htm
2. https://www.geeksforgeeks.org/lists-in-prolog/

Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Rubric Recognition Building Ethics (2)
(2) (2) Total
s (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

47

You might also like