You are on page 1of 21

BABA MASTNATH UNIVERSITY

(Asthal Bohar, Rohtak)

(SESSION :- 2023-2025)
PRACTICLE FILE OF ARTIFICIAL
INTELLIGENCE
SUBMITTED TO :- SUBMITTED BY :-
Dr. ANKIT KUMAR name :- Mo ni ka
ASSISTANT PROFESSOR CLASS :- MCA 2ND SEM.
BMU ROHTAK ROLL NO. :-

DEPARTMENT OF COMPUTER SCIENCE AND


APPLICATIONS
FACULTY OF MANAGEMENT AND COMMERCE
INDEX

Sr. No. Topics Signature

1. Write a program to implement BFS/DFS Traversal?

2. Write simple facts for the statements and querying it.

3. Write a program for Family-tree.

4. Write Program for Monkey-banana Problem.

5. Write a program to implement Tic-Tac-Toe game.

6. Write programs for computation of recursive


functions like factorial Fibonacci numbers, etc.
7. Write program to solve 5-queens problem.

8. Write a Program for water jug problem.

9. Write a program for travelling salesman problem.

10. Write a program to implement all set operations.


1. Write a program to implement BFS/DFS Traversal:

from collections import defaultdict

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)

def bfs(self, start):


visited = set()
queue = [start]
result = []

while queue:
node = queue.pop(0)
if node not in visited:
result.append(node)
visited.add(node)
queue.extend([neighbor for neighbor in self.graph[node] if neighbor not in
visited])

return result

def dfs_util(self, node, visited, result):


visited.add(node)
result.append(node)

for neighbor in self.graph[node]:


if neighbor not in visited:
self.dfs_util(neighbor, visited, result)

def dfs(self, start):


visited = set()
result = []
self.dfs_util(start, visited, result)
return result

# Example usage:
graph = Graph()
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)

print("BFS Traversal:")
print(graph.bfs(2)) # Start BFS from node 2

print("\nDFS Traversal:")
print(graph.dfs(2)) # Start DFS from node 2

Output:
BFS Traversal:
[2, 0, 3, 1]

DFS Traversal:
[2, 0, 1, 3]
2. Write simple facts for the statements and querying it:

class FruitKnowledgeBase:
def __init__(self):
self.facts = {
"Apple": {
"Color": "Red, Green, Yellow",
"Taste": "Sweet or Tart",
"Origin": "Central Asia",
"Nutrition": "Rich in fiber and vitamin C"
},
"Banana": {
"Color": "Yellow",
"Taste": "Sweet",
"Origin": "Southeast Asia",
"Nutrition": "High in potassium and vitamin B6"
},
"Orange": {
"Color": "Orange",
"Taste": "Sweet and tangy",
"Origin": "Southeast Asia",
"Nutrition": "High in vitamin C and fiber"
}
}
def get_fact(self, fruit, fact):
if fruit in self.facts:
if fact in self.facts[fruit]:
return self.facts[fruit][fact]
else:
return "Fact not found for this fruit."
else:
return "Fruit not found in the knowledge base."

# Example usage:
kb = FruitKnowledgeBase()

# Querying facts
print(kb.get_fact("Apple", "Color")) # Output: Red, Green, Yellow
print(kb.get_fact("Banana", "Nutrition")) # Output: High in potassium and vitamin
B6
print(kb.get_fact("Orange", "Origin")) # Output: Southeast Asia
print(kb.get_fact("Mango", "Taste")) # Output: Fruit not found in the knowledge
base.
print(kb.get_fact("Apple", "Shape")) # Output: Fact not found for this fruit.
3. Write a program for Family-tree:

class Person:
def __init__(self, name, gender, father=None, mother=None):
self.name = name
self.gender = gender
self.father = father
self.mother = mother

def __str__(self):
return f"{self.name} ({self.gender})"

class FamilyTree:
def __init__(self):
self.members = {}

def add_member(self, name, gender, father=None, mother=None):


person = Person(name, gender, father, mother)
self.members[name] = person

def get_parent(self, person, parent_type):


if parent_type.lower() == "father":
return person.father
elif parent_type.lower() == "mother":
return person.mother
else:
return None

def print_family_tree(self, person, level=0):


if person:
print(" " * level + str(person))
father = self.get_parent(person, "father")
mother = self.get_parent(person, "mother")
if father:
print(" " * (level + 1) + "Father: ", end="")
self.print_family_tree(father, level + 1)
if mother:
print(" " * (level + 1) + "Mother: ", end="")
self.print_family_tree(mother, level + 1)

# Example usage:
family_tree = FamilyTree()
# Adding family members
family_tree.add_member("John", "Male")
family_tree.add_member("Alice", "Female")
family_tree.add_member("Bob", "Male")
family_tree.add_member("Mary", "Female")
family_tree.add_member("David", "Male", father="John", mother="Alice")
family_tree.add_member("Emma", "Female", father="John", mother="Alice")
family_tree.add_member("Charlie", "Male", father="Bob", mother="Mary")

# Printing family tree


print("Family Tree:")
family_tree.print_family_tree(family_tree.members["John"])

Output:
Family Tree:
John (Male)
Father: Bob (Male)
Mother: Mary (Female)
Father: None
Mother: None
Mother: Alice (Female)
Father: None
Mother: None
Emma (Female)
David (Male)
4. Write Program for Monkey-banana Problem:

class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state
self.parent = parent
self.action = action
self.cost = cost
self.heuristic = heuristic

def __lt__(self, other):


return (self.cost + self.heuristic) < (other.cost + other.heuristic)

class MonkeyBananaProblem:
def __init__(self, initial_state):
self.initial_state = initial_state

def actions(self, state):


actions = []
if state['monkey_location'] == 'A' and state['has_box']:
actions.append('Climb')
actions.append('Push box to B')
elif state['monkey_location'] == 'B' and not state['has_box']:
actions.append('Climb')
actions.append('Push box to A')
elif state['monkey_location'] == 'A' and not state['has_box']:
actions.append('Climb')
elif state['monkey_location'] == 'B' and state['has_box']:
actions.append('Climb')
elif state['monkey_location'] == 'A' and state['has_box']:
actions.append('Push box to B')
elif state['monkey_location'] == 'B' and not state['has_box']:
actions.append('Push box to A')

return actions

def result(self, state, action):


new_state = state.copy()
if action == 'Climb':
new_state['has_banana'] = True
elif action == 'Push box to A':
new_state['monkey_location'] = 'A'
new_state['has_box'] = False
elif action == 'Push box to B':
new_state['monkey_location'] = 'B'
new_state['has_box'] = True

return new_state

def goal_test(self, state):


return state['has_banana']

def heuristic(self, state):


return 1 if state['has_banana'] else 2

def astar_search(self):
frontier = [Node(self.initial_state, None, None, 0,
self.heuristic(self.initial_state))]
explored = set()

while frontier:
frontier.sort()
node = frontier.pop(0)

if self.goal_test(node.state):
actions = []
while node.parent:
actions.insert(0, node.action)
node = node.parent
return actions

explored.add(node.state)

for action in self.actions(node.state):


child_state = self.result(node.state, action)
if child_state not in explored:
new_cost = node.cost + 1
new_node = Node(child_state, node, action, new_cost,
self.heuristic(child_state))
frontier.append(new_node)

return None

# Define the initial state


initial_state = {
'monkey_location': 'A', # Monkey starts at location A
'has_box': False, # Monkey doesn't have the box initially
'has_banana': False # Monkey doesn't have the banana initially
}

# Create the MonkeyBananaProblem instance


monkey_banana_problem = MonkeyBananaProblem(initial_state)

# Solve the problem using A* search


solution = monkey_banana_problem.astar_search()

# Output the solution


if solution:
print("Actions to reach the banana:")
for action in solution:
print(action)
else:
print("No solution found.")
5. Write a program to implement Tic-Tac-Toe game:

class TicTacToe:
def __init__(self):
self.board = [' ' for _ in range(9)]
self.current_winner = None

def print_board(self):
for row in [self.board[i * 3:(i + 1) * 3] for i in range(3)]:
print('| ' + ' | '.join(row) + ' |')

@staticmethod
def print_board_nums():
number_board = [[str(i) for i in range(j * 3, (j + 1) * 3)] for j in range(3)]
for row in number_board:
print('| ' + ' | '.join(row) + ' |')

def available_moves(self):
return [i for i, spot in enumerate(self.board) if spot == ' ']

def empty_squares(self):
return ' ' in self.board

def num_empty_squares(self):
return self.board.count(' ')

def make_move(self, square, letter):


if self.board[square] == ' ':
self.board[square] = letter
if self.winner(square, letter):
self.current_winner = letter
return True
return False

def winner(self, square, letter):


row_ind = square // 3
row = self.board[row_ind*3:(row_ind+1)*3]
if all([spot == letter for spot in row]):
return True

col_ind = square % 3
col = [self.board[col_ind+i*3] for i in range(3)]
if all([spot == letter for spot in col]):
return True

if square % 2 == 0:
diagonal1 = [self.board[i] for i in [0, 4, 8]]
if all([spot == letter for spot in diagonal1]):
return True
diagonal2 = [self.board[i] for i in [2, 4, 6]]
if all([spot == letter for spot in diagonal2]):
return True

return False

def play(game, x_player, o_player, print_game=True):


if print_game:
game.print_board_nums()

letter = 'X'
while game.empty_squares():
if letter == 'O':
square = o_player.get_move(game)
else:
square = x_player.get_move(game)

if game.make_move(square, letter):
if print_game:
print(letter + f' makes a move to square {square}')
game.print_board()
print('')

if game.current_winner:
if print_game:
print(letter + ' wins!')
return letter

letter = 'O' if letter == 'X' else 'X'

if print_game:
print('It\'s a tie!')

class HumanPlayer:
def __init__(self, letter):
self.letter = letter

def get_move(self, game):


valid_square = False
val = None
while not valid_square:
square = input(self.letter + '\'s turn. Input move (0-8): ')
try:
val = int(square)
if val not in game.available_moves():
raise ValueError
valid_square = True
except ValueError:
print('Invalid square. Try again.')
return val

class RandomComputerPlayer:
def __init__(self, letter):
self.letter = letter

def get_move(self, game):


import random
return random.choice(game.available_moves())

if __name__ == '__main__':
x_player = HumanPlayer('X')
o_player = RandomComputerPlayer('O')
t = TicTacToe()
play(t, x_player, o_player, print_game=True)
6. Write programs for computation of recursive functions like factorial
Fibonacci numbers, etc:

// Recursive function for computing factorial:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

# Example usage:
number = 5
print(f"The factorial of {number} is: {factorial(number)}")

Output:
The factorial of 5 is: 120

// Recursive function for computing Fibonacci numbers:

def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)

# Example usage:
number = 6
print(f"The {number}th Fibonacci number is: {fibonacci(number)}")

Output:
The 6th Fibonacci number is: 8
7. Write program to solve 5-queens problem:

class NQueens:
def __init__(self, N):
self.N = N
self.board = [['.' for _ in range(N)] for _ in range(N)]
self.solutions = []

def print_board(self):
for row in self.board:
print(" ".join(row))
print()

def is_safe(self, row, col):


for i in range(self.N):
if self.board[row][i] == 'Q' or self.board[i][col] == 'Q':
return False
if 0 <= row-i < self.N and 0 <= col-i < self.N and self.board[row-i][col-i] ==
'Q':
return False
if 0 <= row-i < self.N and 0 <= col+i < self.N and self.board[row-i][col+i] ==
'Q':
return False
if 0 <= row+i < self.N and 0 <= col-i < self.N and self.board[row+i][col-i] ==
'Q':
return False
if 0 <= row+i < self.N and 0 <= col+i < self.N and self.board[row+i][col+i] ==
'Q':
return False
return True

def solve(self, col=0):


if col == self.N:
self.solutions.append([row[:] for row in self.board])
return True

res = False
for row in range(self.N):
if self.is_safe(row, col):
self.board[row][col] = 'Q'
res = self.solve(col+1) or res
self.board[row][col] = '.'
return res

# Example usage:
n_queens = NQueens(5)
n_queens.solve()

# Print all solutions


for solution in n_queens.solutions:
print("Solution:")
n_queens.board = solution
n_queens.print_board()

Output:
Solution:
Q....
...Q.
.Q...
....Q
..Q..

Solution:
Q....
..Q..
....Q
.Q...
...Q.

Solution:
.Q...
...Q.
Q....
..Q..
....Q

Solution:
.Q...
....Q
..Q..
Q....
...Q.

Solution:
..Q..
Q....
...Q.
.Q...
....Q
8. Write a Program for water jug problem:

from collections import deque

class WaterJugProblem:
def __init__(self, jug1_capacity, jug2_capacity, target_amount):
self.jug1_capacity = jug1_capacity
self.jug2_capacity = jug2_capacity
self.target_amount = target_amount
self.visited_states = set()

def pour(self, state, action):


jug1, jug2 = state
if action == "fill_jug1":
return (self.jug1_capacity, jug2)
elif action == "fill_jug2":
return (jug1, self.jug2_capacity)
elif action == "empty_jug1":
return (0, jug2)
elif action == "empty_jug2":
return (jug1, 0)
elif action == "pour_jug1_to_jug2":
amount_to_pour = min(jug1, self.jug2_capacity - jug2)
return (jug1 - amount_to_pour, jug2 + amount_to_pour)
elif action == "pour_jug2_to_jug1":
amount_to_pour = min(jug2, self.jug1_capacity - jug1)
return (jug1 + amount_to_pour, jug2 - amount_to_pour)

def is_goal_state(self, state):


return state[0] == self.target_amount or state[1] == self.target_amount

def bfs(self):
initial_state = (0, 0)
queue = deque([(initial_state, [])])

while queue:
state, actions = queue.popleft()
if self.is_goal_state(state):
return actions
if state in self.visited_states:
continue
self.visited_states.add(state)
for action in ["fill_jug1", "fill_jug2", "empty_jug1", "empty_jug2",
"pour_jug1_to_jug2", "pour_jug2_to_jug1"]:
new_state = self.pour(state, action)
if new_state not in self.visited_states:
queue.append((new_state, actions + [action]))

return None
# Example usage:
jug1_capacity = 4
jug2_capacity = 3
target_amount = 2

water_jug_problem = WaterJugProblem(jug1_capacity, jug2_capacity,


target_amount)
solution = water_jug_problem.bfs()

if solution:
print("Solution:")
for action in solution:
print(action)
else:
print("No solution found.")

Output:
Solution:
fill_jug2
pour_jug2_to_jug1
empty_jug1
pour_jug2_to_jug1
fill_jug2
pour_jug2_to_jug1
9. Write a program for travelling salesman problem:

import itertools

def distance(point1, point2):


return ((point1[0] - point2[0])**2 + (point1[1] - point2[1])**2) ** 0.5

def total_distance(path, points):


total = 0
for i in range(len(path) - 1):
total += distance(points[path[i]], points[path[i+1]])
total += distance(points[path[-1]], points[path[0]]) # Return to starting point
return total

def traveling_salesman_brute_force(points):
n = len(points)
best_path = None
min_distance = float('inf')

for perm in itertools.permutations(range(n)):


current_distance = total_distance(perm, points)
if current_distance < min_distance:
min_distance = current_distance
best_path = perm

return best_path, min_distance

# Example usage:
cities = [(0, 0), (1, 2), (2, 1), (3, 3)]
best_path, min_distance = traveling_salesman_brute_force(cities)
print("Best path:", best_path)
print("Minimum distance:", min_distance)

Output:
Best path: (0, 2, 1, 3)
Minimum distance: 7.23606797749979
10.Write a program to implement all set operations:

# Define two sets


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# Union
union_set = set1.union(set2)
print("Union:", union_set)

# Intersection
intersection_set = set1.intersection(set2)
print("Intersection:", intersection_set)

# Difference
difference_set = set1.difference(set2)
print("Difference (set1 - set2):", difference_set)

# Symmetric difference
symmetric_difference_set = set1.symmetric_difference(set2)
print("Symmetric Difference:", symmetric_difference_set)

# Subset
subset_check = set1.issubset(set2)
print("Is set1 a subset of set2:", subset_check)

Output:
Union: {1, 2, 3, 4, 5, 6, 7, 8}
Intersection: {4, 5}
Difference (set1 - set2): {1, 2, 3}
Symmetric Difference: {1, 2, 3, 6, 7, 8}
Is set1 a subset of set2: False

You might also like