0% found this document useful (0 votes)
12 views9 pages

AI Dynamic

The document describes various graph algorithms including breadth-first search, depth-first search, A*, Prim's algorithm, solving the n-queen problem using backtracking and branch and bound, graph coloring using backtracking, and creating a basic chatbot using predefined responses.

Uploaded by

aarya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

AI Dynamic

The document describes various graph algorithms including breadth-first search, depth-first search, A*, Prim's algorithm, solving the n-queen problem using backtracking and branch and bound, graph coloring using backtracking, and creating a basic chatbot using predefined responses.

Uploaded by

aarya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

1.

BFS

from collections import deque

def bfs(graph, start, goal):


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

while queue:
node = queue.popleft()
if node not in visited:
print(node)
visited.add(node)
if node == goal:
return True
for neighbour in graph[node]:
if neighbour not in visited:
queue.append(neighbour)
return False

def create_graph():
graph = {}
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
src, dest = input("Enter source and destination node separated by space:
").split()
if src not in graph:
graph[src] = []
if dest not in graph:
graph[dest] = []
graph[src].append(dest)
return graph

def get_goal():
return input("Enter the goal node: ")

def main():
graph = create_graph()
start = 'A' # Assuming start node is 'A'
goal = get_goal()
print("Following is the Breadth First Search:")
bfs(graph, start, goal)

if __name__ == "__main__":
main()
DFS

def dfs(visited, graph, node, goal): # Pass 'goal' as an argument


if node not in visited:
print(node)
visited.add(node)
if node == goal:
return True
for neighbour in graph[node]:
if dfs(visited, graph, neighbour, goal): # Pass 'goal' recursively
return True
return False

def create_graph():
graph = {}
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
src, dest = input("Enter source and destination node separated by space:
").split()
if src not in graph:
graph[src] = []
if dest not in graph:
graph[dest] = []
graph[src].append(dest)
return graph

def get_goal():
return input("Enter the goal node: ")

def main():
graph = create_graph()
goal = get_goal()
visited = set()
print("Following is the Depth First Search:")
dfs(visited, graph, 'A', goal) # Pass 'goal' here

if __name__ == "__main__":
main()
2. A-star

import heapq

class Node:
def __init__(self, state, parent=None, g=0, h=0):
self.state = state
self.parent = parent
self.g = g # Cost from start node to current node
self.h = h # Heuristic estimate from current node to goal node

def f(self):
return self.g + self.h # Total estimated cost of the cheapest solution
through this node

def astar(start, goal, heuristic):


open_set = []
closed_set = set()

heapq.heappush(open_set, (start.f(), start)) # Priority queue ordered by f-


score
while open_set:
_, current_node = heapq.heappop(open_set)

if current_node.state == goal:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return path[::-1] # Return reversed path

closed_set.add(current_node.state)

for neighbor in get_neighbors(current_node.state):


if neighbor in closed_set:
continue

g_score = current_node.g + 1 # Assuming uniform cost for moving


between nodes
h_score = heuristic(neighbor, goal)
new_node = Node(state=neighbor, parent=current_node, g=g_score,
h=h_score)

# Check if this node is already in open set with a lower f-score


in_open_set = any(node.state == new_node.state and node.f() <
new_node.f() for _, node in open_set)
if not in_open_set:
heapq.heappush(open_set, (new_node.f(), new_node))

return None # No path found

def get_neighbors(state):
# Function to get neighbors of a state in the game
pass # Implement according to the game's rules

def heuristic(state, goal):


# Heuristic function estimating cost from state to goal
pass # Implement according to the game's requirements

# Example usage:
start_state = ...
goal_state = ...
start_node = Node(state=start_state)
path = astar(start_node, goal_state, heuristic)
if path:
print("Path found:", path)
else:
print("No path found")

3.prims

INF = 99999999
V = 6
G = [
[0, 1, 9, 0, 0, 0],
[1, 0, 8, 2, 7, 0],
[9, 8, 0, 3, 0, 0],
[0, 2, 3, 0, 4, 6],
[0, 7, 0, 4, 0, 5],
[0, 0, 0, 6, 5, 0]
]
selected = [0, 0, 0, 0, 0, 0]
no_edge = 0
selected[0]=True

while (no_edge < V - 1):


minimum = INF
x = 0
y = 0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
if minimum > G[i][j]:
minimum = G[i][j]
x = i
y = j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

4.(a) n-queen

class NQueens:
def __init__(self, n):
self.n = n
self.board = [-1] * n

def is_safe(self, row, col):


for prev_row in range(row):
prev_col = self.board[prev_row]
if prev_col == col or prev_col - prev_row == col - row or prev_col +
prev_row == col + row:
return False
return True

def solve_backtracking(self, row=0):


if row == self.n:
return True
for col in range(self.n):
if self.is_safe(row, col):
self.board[row] = col
if self.solve_backtracking(row + 1):
return True
self.board[row] = -1
return False

def solve_branch_and_bound(self, row=0, col_min=0):


if row == self.n:
return True
for col in range(col_min, self.n):
if self.is_safe(row, col):
self.board[row] = col
if self.solve_branch_and_bound(row + 1, col + 1):
return True
self.board[row] = -1
return False

def print_solution(self):
for row in range(self.n):
line = ['Q' if col == self.board[row] else '.' for col in
range(self.n)]
print(' '.join(line))

# Example usage:
n = 8
queens = NQueens(n)

print("Backtracking Solution:")
if queens.solve_backtracking():
queens.print_solution()
else:
print("No solution found")

print("\nBranch and Bound Solution:")


if queens.solve_branch_and_bound():
queens.print_solution()
else:
print("No solution found")
4(b). coloring

class GraphColoring:
def __init__(self, graph, num_colors):
self.graph = graph
self.num_colors = num_colors
self.colors = [0] * len(graph)

def is_safe(self, vertex, color):


for neighbor in self.graph[vertex]:
if self.colors[neighbor] == color:
return False
return True

def solve_backtracking(self, vertex=0):


if vertex == len(self.graph):
return True
for color in range(1, self.num_colors + 1):
if self.is_safe(vertex, color):
self.colors[vertex] = color
if self.solve_backtracking(vertex + 1):
return True
self.colors[vertex] = 0
return False

def print_solution(self):
for i, color in enumerate(self.colors):
print(f"Vertex {i}: Color {color}")

# Example usage:
graph = {
0: [1, 2, 3],
1: [0, 2],
2: [0, 1, 3],
3: [0, 2]
}
num_colors = 3

coloring = GraphColoring(graph, num_colors)


if coloring.solve_backtracking():
print("Solution found:")
coloring.print_solution()
else:
print("No solution found")
5. chatbot

import random

# Predefined responses
greetings = ["Hello!", "Hi there!", "Hey!", "Greetings!"]
options = ["How can I assist you today?", "What can I do for you?", "How may I help
you?"]
farewells = ["Goodbye!", "See you later!", "Until next time!", "Have a great day!"]

# Function to generate a random greeting


def greet():
return random.choice(greetings)

# Function to handle user input and generate response


def respond(user_input):
if "help" in user_input:
return "Sure, I can help you with that!"
elif "order" in user_input:
return "To place an order, please visit our website."
elif "complaint" in user_input:
return "I'm sorry to hear that. Please provide details of your complaint,
and we'll do our best to resolve it."
elif "thank" in user_input:
return "You're welcome! If you need anything else, feel free to ask."
elif "bye" in user_input:
return random.choice(farewells)
else:
return "I'm sorry, I didn't understand. Can you please rephrase your
request?"

# Main function to interact with the user


def chatbot():
print(greet())
print(random.choice(options))
while True:
user_input = input("You: ").lower()
if user_input == "exit":
print(random.choice(farewells))
break
response = respond(user_input)
print("Chatbot:", response)
# Start the conversation
chatbot()

cc 3.oldaccount

public class OlderAccountsUtility {


public static void updateOlderAccounts() {
List<Account> oldAccounts = [SELECT Id, Description FROM Account
ORDER BY CreatedDate ASC LIMIT 5];

for (Account acct : oldAccounts) {


acct.Description += '5';
}

update oldAccounts;
}
}

OlderAccountsUtility.updateolderAccounts();

You might also like