0% found this document useful (0 votes)
6 views5 pages

AI Python

The document outlines various algorithms for search and problem-solving, including breadth-first search (BFS), depth-first search (DFS), uniform cost search (UCS), heuristic search strategies like A*, hill climbing, and backtracking for constraint satisfaction problems (CSP). Each algorithm is accompanied by Python code examples demonstrating their implementation on sample graphs. Additionally, a simple rule-based chatbot is included to illustrate basic user interaction.

Uploaded by

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

AI Python

The document outlines various algorithms for search and problem-solving, including breadth-first search (BFS), depth-first search (DFS), uniform cost search (UCS), heuristic search strategies like A*, hill climbing, and backtracking for constraint satisfaction problems (CSP). Each algorithm is accompanied by Python code examples demonstrating their implementation on sample graphs. Additionally, a simple rule-based chatbot is included to illustrate basic user interaction.

Uploaded by

rohini.r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Get input 1

Get input 2

Get the operation to be done

return output of input 1 (operation) input 2

### Get the expression in a single statment and perform ### ##### Get the statmement and
split by space as a delimiter ##### ##### The output you get are tokens ##### #####
Perform operation using tokens #####

Get the input as multiple numbers and multiple operators combined and perform
Get the statement

split the statement into tokens

format expression

print result

Simple Rule Based Chatbot


def chatbot(user_input):
responses = {
"hello": "Hi there! How can I help you today?",
"weather": "I'm not connected to a sensor, but it looks sunny
in code-land!",
"bye": "Goodbye! Have a great day."
}
return [Link](user_input.lower(), "I'm still learning!
Could you rephrase?")

q = input('Am listening:')
print(chatbot(q))

Am listening: hello

Hi there! How can I help you today?

Breadth First Search (BFS)


from collections import deque
def bfs(graph, start, goal):
queue = deque([[start]])
visited = set()
while queue:
path = [Link]()
node = path[-1]
if node == goal: return path
if node not in visited:
for neighbor in [Link](node, []):
new_path = list(path)
new_path.append(neighbor)
[Link](new_path)
[Link](node)
return None
graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E':
[], 'F': []}

from_ = input('Starting node:').upper()


to_ = input('Ending node:').upper()
print(f"Path A to F: {bfs(graph, from_, to_)}")

Starting node: a
Ending node: e

Path A to F: ['A', 'B', 'E']

Depth First Search (DFS)


def dfs(graph, start, goal):
# Stack stores tuples of (current_node, path_taken)
stack = [(start, [start])]
visited = set()

while stack:
(vertex, path) = [Link]()

if vertex not in visited:


if vertex == goal:
return path

[Link](vertex)

# Add neighbors to stack


for neighbor in reversed([Link](vertex, [])):
if neighbor not in visited:
[Link]((neighbor, path + [neighbor]))
return None

# Sample Unweighted Graph


graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
path = dfs(graph, 'A', 'F')
print(f"DFS Path from A to F: {path}")

Uniform Cost Search (UCS)


import heapq

def ucs(graph, start, goal):


# Priority Queue stores tuples of (cumulative_cost, current_node,
path)
# heapq always pops the element with the smallest cumulative_cost
priority_queue = [(0, start, [start])]
visited = {} # Stores node: minimum_cost_to_reach

while priority_queue:
(cost, node, path) = [Link](priority_queue)

# If we reached the goal, because it's UCS, this is the


cheapest path
if node == goal:
return path, cost

if node not in visited or cost < visited[node]:


visited[node] = cost

for neighbor, weight in [Link](node, {}).items():


new_cost = cost + weight
[Link](priority_queue, (new_cost, neighbor,
path + [neighbor]))

return None, float('inf')

# Sample Weighted Graph


# Format: { 'Node': {'Neighbor': Cost} }
weighted_graph = {
'A': {'B': 2, 'C': 5},
'B': {'D': 2, 'E': 4},
'C': {'G': 6},
'D': {'G': 1},
'E': {'G': 1},
'G': {}
}

path, total_cost = ucs(weighted_graph, 'A', 'G')


print(f"UCS Cheapest Path from A to G: {path} with total cost:
{total_cost}")
Heuristic Search Strategies (Informed Search)Concept:
Uses problem-specific knowledge (heuristics) to find solutions more efficiently.

*A Search:** The most popular informed search. #####

It uses f ( n )=g ( n ) +h ( n ), where g ( n ) is the cost to reach the node and h ( n ) is the estimated cost to
the goal.

Real-World Example: Google Maps. It uses A* to find the shortest driving path by estimating the "as-
the-crow-flies" distance to your destination.
def manhattan_distance(curr, goal):
return abs(curr[0] - goal[0]) + abs(curr[1] - goal[1])

start, goal = (0, 0), (7, 5)


print(f"Heuristic estimate: {manhattan_distance(start, goal)}")

Hill Climbing
import random

def hill_climbing(function, start_x):


current_x = start_x
while True:
neighbor = current_x + [Link](-0.1, 0.1)
if function(neighbor) <= function(current_x):
return current_x
current_x = neighbor

# Example: Finding the top of a simple parabola


print(f"Peak found near: {hill_climbing(lambda x: -(x**2) + 5,
[Link](-10, 10))}")

Backtracking for CSP


def is_safe(node, color, graph, colors):
for neighbor in graph[node]:
if [Link](neighbor) == color:
return False
return True

def solve_csp(node, graph, available_colors, colors):


if node is None: return True
for color in available_colors:
if is_safe(node, color, graph, colors):
colors[node] = color
# Simplified: move to next node
next_node = list([Link]())
[list([Link]()).index(node)+1] if node != 'C' else None
if solve_csp(next_node, graph, available_colors, colors):
return True
colors[node] = None
return False

graph = {'A': ['B'], 'B': ['A', 'C'], 'C': ['B']}


assigned_colors = {}
solve_csp('A', graph, ['Red', 'Green'], assigned_colors)
print(f"Color assignment: {assigned_colors}")

You might also like