Experiment No: 4: Artificial Intelligence (3170716)
Experiment No: 4: Artificial Intelligence (3170716)
Experiment No: 4: Artificial Intelligence (3170716)
Experiment No: 4
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:
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.
• 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.
Artificial Intelligence (3170716) 210170107518
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:
Conclusion:
The Prolog program and its associated semantic network depict a series of relationships and facts.
It classifies Tom and Cat1 as cats, each being mammals and animals. Tom is further defined as
having ginger fur and being owned by John. Cat1 is shown to sit on Mat1, while Tom has caught
Bird1, establishing a predator-prey relationship. The program introduces a rule that entities liking
cream are considered cats, allowing for a simple form of inference. Overall, this Prolog program
provides a structured representation of entities, their attributes, ownership, and actions,
demonstrating the utility of Prolog in encoding and reasoning about relationships in a logical
manner.
Quiz:
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)
1. https://rashandeepsingh.medium.com/what-is-semantic-net-give-example-1757afa43ea6
2. https://lucid.app/documents#/documents?folder_id=recent
Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 5
Date:
Theory:
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:
Sentences are represented as a series of diagrams depicting actions using both abstract and
real physical situations.
ATRANS
-- Transfer of an abstract relationship. e.g. give.
PTRANS
-- Transfer of the physical location of an object. e.g. go.
PROPEL
Artificial Intelligence (3170716) 210170107518
-- Application of a physical force to an object. e.g. push.
MTRANS
-- Transfer of mental information. e.g. tell.
MBUILD
-- Construct new information from old. e.g. decide.
SPEAK
-- Utter a sound. e.g. say.
ATTEND
-- Focus a sense on a stimulus. e.g. listen, watch.
MOVE
-- Movement of a body part by owner. e.g. punch, kick.
GRASP
-- Actor grasping an object. e.g. clutch.
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.
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:
Artificial Intelligence (3170716) 210170107518
p
-- past
f
-- future
t
-- transition
-- start transition
-- finished transition
k
-- continuing
?
-- interrogative
/
-- negative
delta
-- timeless
c
-- conditional
the absence of any modifier implies the present tense.
Advantages of CD:
Disadvantages of CD:
• Primitive actions are the basic actions that can be performed or described without reference
to other actions or concepts
Procedure:
Conclusion:
In analyzing the two sentences, it's evident that Conceptual Dependency (CD) offers a structured
and formal method for representing the meaning of natural language statements. In the first
sentence, "John gives Mary a book," the CD model efficiently captures the key components of the
action: the agent, John; the action, give; and the object, a book, which has both recipient, Mary, and
thematic elements. In the second sentence, "John gave Mary the book yesterday," CD extends its
utility by incorporating temporal information, making it possible to represent events in the context
of time. CD proves to be a valuable tool for breaking down and visualizing the intricate relationships
and dependencies within sentences, enhancing our understanding of the underlying semantics and
facilitating natural language processing tasks.
Quiz:
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)
1. https://people.cs.pitt.edu/~wiebe/courses/CS3730/Spring2013/cd.pdf
2. https://users.cs.cf.ac.uk/Dave.Marshall/AI2/node69.html
Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 6
Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.
Date:
Objectives: To illustrate how to recursively apply the Minimax algorithm to build a game tree
and determine the optimal move for the computer player.
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.
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.
Artificial Intelligence (3170716) 210170107518
3. Create a function to get the best move for the current player.
Observation/Program:
PLAYER_X = 'X'
PLAYER_O = 'O'
EMPTY = ' '
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def is_draw(board):
return all(board[i][j] != EMPTY for i in range(3) for j in range(3))
def available_moves(board):
return [(i, j) for i in range(3) for j in range(3) if board[i][j] == EMPTY]
if is_maximizing:
max_eval = -float('inf')
for move in available_moves(board):
i, j = move
board[i][j] = PLAYER_X
eval = minimax(board, depth + 1, False)
board[i][j] = EMPTY
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float('inf')
Artificial Intelligence (3170716) 210170107518
for move in available_moves(board):
i, j = move
board[i][j] = PLAYER_O
eval = minimax(board, depth + 1, True)
board[i][j] = EMPTY
min_eval = min(min_eval, eval)
return min_eval
def find_best_move(board):
best_eval = -float('inf')
best_move = None
return best_move
if __name__ == "__main__":
board = [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
print("Welcome to Tic-Tac-Toe!")
print_board(board)
while True:
player_move = input("Enter your move (row and column, e.g., '0 0'): ").split()
i, j = int(player_move[0]), int(player_move[1])
if board[i][j] != EMPTY:
print("Invalid move. Try again.")
continue
board[i][j] = PLAYER_O
print_board(board)
if is_winner(board, PLAYER_O):
print("You win! Congratulations!")
break
if is_draw(board):
print("It's a draw!")
break
computer_move = find_best_move(board)
Artificial Intelligence (3170716) 210170107518
i, j = computer_move
board[i][j] = PLAYER_X
print("Computer's move:")
print_board(board)
if is_winner(board, PLAYER_X):
print("Computer wins!")
break
if is_draw(board):
print("It's a draw!")
break
Conclusion:
Artificial Intelligence (3170716) 210170107518
The Minimax algorithm is a fundamental technique for decision-making in two-player games like
tic-tac-toe. The code provided effectively implements the Minimax algorithm, constructing a game
tree and evaluating game states with an evaluation function. It handles edge cases and ensures that
the game proceeds smoothly. This algorithm, when applied to a game, allows the AI player to make
optimal moves by considering all possible future outcomes, making it a powerful tool for game AI
development.
Quiz:
1. How can you optimize the Minimax algorithm to improve its performance in Tic Tac
Toe?
To optimize the Minimax algorithm in Tic Tac Toe, you can use alpha-beta pruning to
reduce the number of evaluated game states and improve 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 a wide range of two-player, deterministic
games, including chess, checkers, and Connect Four, not just Tic Tac Toe.
Artificial Intelligence (3170716) 210170107518
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
1. https://www.shiksha.com/online-courses/articles/tic-tac-game-python/
2. https://www.shiksha.com/online-courses/articles/tic-tac-game-python/
3. https://geekflare.com/tic-tac-toe-python-code/
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
Artificial Intelligence (3170716) 210170107518
Experiment No: 7
Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.
Date:
Objectives: To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.
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.
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
Artificial Intelligence (3170716) 210170107518
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.
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:
Conclusion:
Here , we have used an pgmpy module for implementation of Bayesian network with probabilistic
distribution the module contains all the work necessary to implement monty hall problem .
The work was as below . first of all we define the Options for contestant and their probabllity
distribution contestent{1,2,3} Prizes {1,2,3} Host {1,2,3} .
After that train the model and then query it based on the options chosen by contestant and host .
And then model return the output probability for each option and based on that we have to decide
either contastent has to switch or not .
Artificial Intelligence (3170716) 210170107518
We have query it by saying that contestant has chosen door 0 and host has chosen door 2 but the
probability distribution says that door 1 has high probability of the desire prize so contestant has to
Switch the door and accept the offer.
Quiz:
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
1. https://ipython.readthedocs.io/en/stable/install/kernel_install.html
2. https://en.wikipedia.org/wiki/Monty_Hall_problem
Marks
Artificial Intelligence (3170716) 210170107518
Experiment No: 8
Date:
Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.
Objectives:Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.
Theory:
Connectionist Models
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:
• 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.
Artificial Intelligence (3170716) 210170107518
Different tools are designed for different tasks, and it's crucial to use a tool that is
appropriate for the task at hand.
Procedure:
Observation/Program:
Preprocessing
from sklearn.preprocessing import LabelEncoder
input_encoder = LabelEncoder()
output_encoder = LabelEncoder()
for col in x_columns:
data[col] = output_encoder.fit_transform(data[col])
X = data[x_columns]
Counting score
score = accuracy_score(y_test, y_predicted)
in neural network we have 6 layers first layer take all the input features and last layer predict the all
the output fratures all the middle layers have 256 nodes with relu activation method . and last layer
was producing the output that’s why it has softmax activation function .
Observations:
Input Data to feed into the model 64 features
Artificial Intelligence (3170716) 210170107518
Output Classes
Conclusion:
So I have created an small data science project here . I have downloaded an dataset called chess
best move predictor on kaggle which is already cleaned so our work will be easy today.
I feed the data into the neural network with following properties .
Neural network has 1 input layer , 4 hidden layers and 1 output layers .
Input layer has 64 input features while all the hidden layers has 256 internal nodes .
Input layer and all hidden layer uses relu activation while output layer used softmax activation.
I have also added some visuals to compare the efficiency of the predicted output and actual output.
Loss function is sparse_categorical_crossentropy and optimizer is adam .
Quiz:
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
1. https://aws.amazon.com/what-is/neural-
network/#:~:text=A%20neural%20network%20is%20a,that%20resembles%20the%20hum
an%20brain.
2. https://www.ibm.com/topics/neural-networks
Artificial Intelligence (3170716) 210170107518
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
Artificial Intelligence (3170716) 210170107518
Experiment No: 9
Date:
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
Objectives: To use a computational approach that mimics the process of natural selection to solve
optimization problems
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.
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
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).
Artificial Intelligence (3170716) 210170107518
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:
Observation/Program:
Code:
import random
for _ in range(num_parents):
spin = random.uniform(0, total_fitness)
cumulative_fitness = 0
return parents
return offspring
for i in range(len(mutated_individual)):
if random.random() < mutation_rate:
mutated_individual[i] = '0' if individual[i] == '1' else '1'
return ''.join(mutated_individual)
Artificial Intelligence (3170716) 210170107518
if __name__ == "__main__":
target_string = input("Enter the target string: ")
population = ["".join(random.choice("01") for _ in range(len(target_string))) for _ in range(3)]
mutation_rate = 0.1
while True:
e = input("Options: [S]election, [C]rossover, [M]utation, [E]xit: ")
if e == "s" or e == "S":
fitness_scores = [sum(1 for a, b in zip(target_string, individual) if a == b) for individual in
population]
num_parents = 2
selected_parents = proportional_selection(population, fitness_scores, num_parents)
print("Selected Parents:")
for parent in selected_parents:
print(parent)
elif e == "c" or e == "C":
if len(population) < 2:
print("Need at least 2 individuals in the population for crossover.")
continue
parent1, parent2 = random.sample(population, 2)
offspring = one_point_crossover(parent1, parent2)
print("Offspring:", offspring)
population.append(offspring)
elif e == "m" or e == "M":
mutated_population = [mutate(individual, mutation_rate) for individual in population]
print("Mutated Population:")
for mutated_individual in mutated_population:
print(mutated_individual)
population.append(mutated_individual)
elif e == "e" or e == "E":
break
Conclusion:
Artificial Intelligence (3170716) 210170107518
In conclusion, the provided code offers a foundational understanding of how GAs work, but
practical implementations should consider the problem's specific requirements and necessitate
careful design and validation of the fitness function and other algorithm parameters to achieve
meaningful results in various AI and optimization domains.
Quiz:
1. What are the genetic operators that will be used to create new individuals in each
generation? Will you use crossover, mutation, or both?
Genetic operators typically include both crossover (recombining genetic material from two
parents) and mutation (introducing small random changes). Both are commonly used in
genetic algorithms.
2. How will you evaluate the fitness of each individual in the population? Will you evaluate
them sequentially or in parallel?
The fitness of each individual is evaluated based on a predefined fitness function. Evaluation
can be done sequentially or in parallel, depending on available resources.
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. It could be based on reaching a
certain fitness level, a fixed number of generations, or when convergence criteria are met,
depending on the specific problem and goals.
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
1. https://www.geeksforgeeks.org/genetic-algorithms/
2. https://www.javatpoint.com/genetic-algorithm-in-machine-learning
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
Artificial Intelligence (3170716) 210170107518
Experiment No: 10
Date:
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 –
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
list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.
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.
Delete Items This operation removes the specified element from a list.
Append Items Append operation adds one list into another (as an item).
The program should handle exceptions, such as input errors or invalid operations.
Procedure:
Observation/Program:
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
Artificial Intelligence (3170716) 210170107518
list_cancat([],L,L).
list_concat([X1|L1],L2,[X1|L3]):- list_concat(L1,L2,L3).
list_member(X,[X|_]).
list_member(X,[_|TAIL]) :- list_member(X,TAIL).
list_append(A,T,T) :- list_member(A,T),!.
list_append(A,T,[A|T]).
list_insert(X,L,R) :- list_delete(X,R,L).
Artificial Intelligence (3170716) 210170107518
Conclusion:
In this practical we have done the prolog programing in symbolic language and write the prolog
code for various list operations such as searching , appending , inserting and delete .it’s a fun
activity we have done here inspite the logic was not so hard but the preciseness in the logic should
be required in order to achieve the desired output .
Quiz:
2) Write a Prolog predicate "last/2" that returns the last element of a list.
Here's a Prolog predicate "last/2" that returns the last element of a list:
last(X, [X]).
last(X, [_|T]) :- last(X, T).
This predicate checks if the input list has only one element, in which case that element is the
last. If the list has more than one element, it recursively removes the first element and
continues until it reaches the last element.
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/
1. https://www.javatpoint.com/lists-and-sequence-in-prolog
2. https://www.geeksforgeeks.org/lists-in-prolog/
3. https://www.tutorialspoint.com/prolog/prolog_lists.htm
Artificial Intelligence (3170716) 210170107518
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