BFS

graph = {

 'A': set(['B', 'C']),
 'B': set(['A', 'D', 'E']),
 'C': set(['A', 'F']),
 'D': set(['B']),
 'E': set(['B', 'F']),
 'F': set(['C', 'E'])
}
def bfs(start):
 queue = [start]
 levels = {}
 levels[start] = 0
 visited = set([start])
 while queue:
     node = queue.pop(0)
     neighbours = graph[node]
     for neighbor in neighbours:
         if neighbor not in visited:
             queue.append(neighbor)
             visited.add(neighbor)
             levels[neighbor] = levels[node] + 1
 print(levels)
 return visited
print(str(bfs('A'))) 

DFS
graph1 = {
 'A': set(['B', 'C']),
 'B': set(['A', 'D', 'E']),
 'C': set(['A', 'F']),
 'D': set(['B']),
 'E': set(['B', 'F']),
 'F': set(['C', 'E']),
}
def dfs(graph, node, visited):
 if node not in visited:
     visited.append(node)
     for neighbor in graph[node]:
         dfs(graph, neighbor, visited)
 return visited
visited = dfs(graph1, 'A', [])
print(visited)

tower of Hanoi

def moveTower(height, fromPole, toPole, withPole):
 if height >= 1:
     moveTower(height - 1, fromPole, withPole, toPole)
     movedisk(fromPole, toPole)
     moveTower(height - 1, withPole, toPole, fromPole)
def movedisk(fp, tp):
 print("moving disk from", fp, "to", tp)
moveTower(3, "A", "B", "C") 

Alpha beta
IN COMMAND PROMPT
 A. Write a program to implement A* algorithm.
 B. Write a program to implement AO* algorithm.
from simpleai.search import SearchProblem, astar 
GOAL = 'HELLO WORLD' 
class HelloProblem(SearchProblem): 
    def actions(self, state): 
        if len(state) < len(GOAL): 
            return list(' ABCDEFGHIJKLMNOPQRSTUVWXYZ') 
        else: 
            return [] 
    def result(self, state, action): 
        return state + action 
    def is_goal(self, state): 
        return state == GOAL 
    def heuristic(self, state): 
        wrong = sum([1 if state[i] != GOAL[i] else 0 
                     for i in range(len(state))]) 
        missing = len(GOAL) - len(state) 
        return wrong + missing 
problem = HelloProblem(initial_state='') 
result = astar(problem) 
print(result.state) 
print(result.path())
Water jug