AI Lab QB
AI Lab QB
1. sum(X, Y, Z): This states that something is the sum of X and Y if it satisfies
the conditions mentioned in the Body.
2. Read the Body:
Z is X + Y: This condition states that Z is the result of adding X and Y.
3. Putting it together:
The rule can be read as: "Something is the sum of X and Y if Z is the result of
adding X and Y."
1. Read the Head:
father(Father, Child): This states that something is a father if it
satisfies the conditions mentioned in the Body.
2. Read the Body:
parent(Father, Child): This condition states that Father is a parent of
Child.
male(Father): This condition states that Father is male.
3. Putting it together:
The rule can be read as: "Someone is a father of a child if they are the
parent of that child and they are male."
Example program:
parent(john, jim).
parent(john, ann).
parent(jim, pat).
parent(pat, kate).
parent(john, jim).
parent(john, ann).
parent(jim, pat).
parent(sarah, jim).
fibonacci(0, 0).
fibonacci(1, 1).
fibonacci(N, Sequence) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fibonacci(N1,Sequence1),
fibonacci(N2, Sequence2),
Sequence is Sequence1 + Sequence2.
4. Write a Prolog program to solve the Tower of Hanoi problem. The predicate
`hanoi(N)` should give the steps to solve a Tower of Hanoi puzzle with N
disks.
def reverse(input_str):
return input_str[::-1]
def main():
my_string = input("Enter a string: ")
rev = reverse(my_string)
print("Reversed string:", rev)
if __name__ == "__main__":
main()
6. Write a Python function `caesar_cipher(input_str, shift)` that
implements a simple Caesar cipher, which is a type of substitution cipher
in which each letter in the plaintext is 'shifted' a certain number of places
down the alphabet.
output_str = ""
for char in input_str:
if char.isalpha():
output_str += chr((ord(char) + shift - ord('a')) % 26+ord('a'))
else:
output_str += char
return output_str
if __name__ == "__main__":
input_str = "Hello, world!"
shift = 3
encrypted_str = caesar_cipher(input_str, shift)
print(encrypted_str)
def tic_tac_toe(board):
# Check rows
for row in board:
if row.count('X') == 3:
return 'X'
elif row.count('O') == 3:
return 'O'
# Check columns
for col in range(3):
if board[0][col] == board[1][col] == board[2][col] == 'X':
return 'X'
elif board[0][col] == board[1][col] == board[2][col] == 'O':
return 'O'
# Check diagonals
if board[0][0] == board[1][1] == board[2][2] == 'X' or board[0][2] ==
board[1][1] == board[2][0] == 'X':
return 'X'
elif board[0][0] == board[1][1] == board[2][2] == 'O' or board[0][2]
== board[1][1] == board[2][0] == 'O':
return 'O'
# No winner
return 'Neither'
# Example board
board = [
['X', 'O', 'O'],
['X', 'X', 'O'],
['O', 'X', 'X']
]
winner = tic_tac_toe(board)
print("The winner is", winner)
def main():
# Create a graph represented as a dictionary
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}
start_node = 'A'
print("BFS Traversal:")
bfs(graph, start_node)
if __name__ == '__main__':
main()
while stack:
node = stack.pop() # Get the next node from the stack
if node not in visited:
visited.add(node) # Mark node as visited
print(node) # You can modify this line to perform any desired
operation on the node
def main():
# Create a graph represented as a dictionary
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
start_node = 'A'
print("DFS Traversal:")
dfs(graph, start_node)
if __name__ == '__main__':
main()
Write a Python function `best_first_search(graph, start_node, goal_node, heuristic)`
that performs a best-first search on a given graph, starting from a given node and
aiming for a goal node. The heuristic function will be provided and takes two nodes
as input, returning an estimate of the cost to reach the goal from the first node.
# No path exists
return None
Args:
graph: A graph represented as a dictionary where the keys are nodes and
the values are lists of neighbors.
start_node: The start node of the path.
goal_node: The goal node of the path.
visited: A set containing the visited nodes during the search.
Returns:
A list of nodes representing the path from the start node to the goal
node.
"""
path = [goal_node]
current_node = goal_node
return path
# Example usage
def heuristic(node1, node2):
# Example heuristic function (returning a constant value for demonstration
purposes)
return 1
def main():
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}
start_node = 'A'
goal_node = 'F'
if __name__ == '__main__':
main()
import heapq
while queue:
# Get the node with the lowest f-value from the priority queue
f_value, current_node = heapq.heappop(queue)
# If the neighbor has not been visited or the new path has a lower cost,
# update the cost and parent information, and add the neighbor to the queue
if neighbor not in cost or g_value < cost[neighbor]:
cost[neighbor] = g_value
parent[neighbor] = current_node
heapq.heappush(queue, (f_value, neighbor))
# Example usage:
# Define the graph as a dictionary of dictionaries
graph = {
'A': {'B': 5, 'C': 3},
'B': {'D': 2},
'C': {'D': 8, 'E': 10},
'D': {'E': 2, 'F': 6},
'E': {'F': 1},
'F': {}
}
start_node = 'A'
goal_node = 'F'
import heapq
# Create a dictionary to store the shortest distances from the start node to
each node
distances = {node: float('inf') for node in graph}
distances[start_node] = 0
# Skip this node if its distance is already greater than the distance from the
start node
if distance > distances[current_node]:
continue
# If the new distance is shorter, update the distance and previous information
if total_distance < distances[neighbor]:
distances[neighbor] = total_distance
previous[neighbor] = current_node
heapq.heappush(queue, (total_distance, neighbor))
# Example usage:
# Define the graph as a dictionary of dictionaries
graph = {
'A': {'B': 5, 'C': 3},
'B': {'D': 2},
'C': {'D': 8, 'E': 10},
'D': {'E': 2, 'F': 6},
'E': {'F': 1},
'F': {}
}
start_node = 'A'
end_node = 'F'