Sei sulla pagina 1di 11

Q1: What is difference between Graph and Tree?

Trees vs. Graphs. Tree is special form of graph i.e. minimally connected graph and having only
one path between any two vertices. Tree is a special case of graph having no loops, no circuits
and no self-loops. Graph can have loops, circuits as well as can have self-loops.

Q2: What is difference between informed and uninformed searches


?
An uninformed search is a searching technique that has no additional information about the
distance from the current state to the goal.
Informed Search is another technique that has additional information about the estimate distance
from the current state to the goal.

Basis of Informed search Uninformed search


comparison

Basic knowledge Uses knowledge to find the steps to No use of knowledge


the solution.

Efficiency Highly efficient as consumes less time Efficiency is mediatory


and cost.

Cost Low Comparatively high

Performance Finds the solution more quickly. Speed is slower than the informed search.

Algorithms Heuristic depth-first and breadth-first Depth-first search, breadth-first search, and
search, and A* search lowest cost first search

Q3: What is heuristic search?

A Heuristic is a technique to solve a problem faster than classic methods, or to find an


approximate solution when classic methods cannot. This is a kind of a shortcut as we often trade
one of optimality, completeness, accuracy, or precision for speed. A Heuristic (or a heuristic
function) takes a look at search algorithms. At each branching step, it evaluates the available
information and makes a decision on which branch to follow. It does so by ranking alternatives.
The Heuristic is any device that is often effective but will not guarantee work in every case.

So why do we need heuristics? One reason is to produce, in a reasonable amount of time, a


solution that is good enough for the problem in question. It doesn’t have to be the best- an
approximate solution will do since this is fast enough. Most problems are exponential. Heuristic
Search let us reduce this to a rather polynomial number. We use this in AI because we can put it
to use in situations where we can’t find known algorithms.
We can say Heuristic Techniques are weak methods because they are vulnerable to
combinatorial explosion.

Genetic Algorithm
CODE:
import random
X=int(input())
POPULATION_SIZE = X
Y=int(input())
TARGET=Y
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}'''
TARGET = "DASH"
class Individual(object):
'''
Class representing individual in population
'''

def __init__(self, chromosome):


self.chromosome = chromosome
self.fitness = self.cal_fitness()

@classmethod
def mutated_genes(self):
'''
create random genes for mutation
'''
global GENES
gene = random.choice(GENES)
return gene

@classmethod
def create_gnome(self):
'''
create chromosome or string of genes
'''
global TARGET
gnome_len = len(TARGET)
return [self.mutated_genes() for _ in range(gnome_len)]

def mate(self, par2):


'''
Perform mating and produce new offspring
'''
child_chromosome = []
for gp1, gp2 in zip(self.chromosome, par2.chromosome):

prob = random.random()

if prob < 0.45:


child_chromosome.append(gp1)

elif prob < 0.90:


child_chromosome.append(gp2)

else:
child_chromosome.append(self.mutated_genes())

return Individual(child_chromosome)

def cal_fitness(self):
'''
Calculate fittness score, it is the number of
characters in string which differ from target
string.
'''
global TARGET
fitness = 0
for gs, gt in zip(self.chromosome, TARGET):
if gs != gt: fitness += 1
return fitness

# Driver code

def main():
global POPULATION_SIZE

# current generation
generation = 1
found = False
population = []

# create initial population


for _ in range(POPULATION_SIZE):
gnome = Individual.create_gnome()
population.append(Individual(gnome))

while not found:

# sort the population in increasing order of fitness score


population = sorted(population, key=lambda x: x.fitness

if population[0].fitness <= 0:
found = True
break

# Otherwise generate new offsprings for new generation


new_generation = []

s = int((10 * POPULATION_SIZE) / 100)


new_generation.extend(population[:s])

s = int((90 * POPULATION_SIZE) / 100)


for _ in range(s):
parent1 = random.choice(population[:50])
parent2 = random.choice(population[:50])
child = parent1.mate(parent2)
new_generation.append(child)

population = new_generation

print("Generation: {}\tString: {}\tFitness: {}". \


format(generation,
"".join(population[0].chromosome),
population[0].fitness))

generation += 1

print("Generation: {}\tString: {}\tFitness: {}". \


format(generation,
"".join(population[0].chromosome),
population[0].fitness))

if __name__ == '__main__':
main()
Hill claiming

import math

increment = 0.1
#startingPoint = [1, 1]
startingPoint=[]
for i in range(2):
x=int(input("Enter starting point: "))
startingPoint.append(x)

point1 = [1,5]
point2 = [6,4]
point3 = [5,2]
point4 = [2,1]

def distance(x1, y1, x2, y2):


dist = math.pow(x2-x1, 2) + math.pow(y2-y1, 2)
return dist

def sumOfDistances(x1, y1, px1, py1, px2, py2, px3, py3, px4, py4):
d1 = distance(x1, y1, px1, py1)
d2 = distance(x1, y1, px2, py2)
d3 = distance(x1, y1, px3, py3)
d4 = distance(x1, y1, px4, py4)

return d1 + d2 + d3 + d4

def newDistance(x1, y1, point1, point2, point3, point4):


d1 = [x1, y1]
d1temp = sumOfDistances(x1, y1, point1[0],point1[1], point2[0],point2[1],
point3[0],point3[1], point4[0],point4[1] )
d1.append(d1temp)
return d1
minDistance = sumOfDistances(startingPoint[0], startingPoint[1], point1[0],point1[1],
point2[0],point2[1],
point3[0],point3[1], point4[0],point4[1] )
flag = True

def newPoints(minimum, d1, d2, d3, d4):


if d1[2] == minimum:
return [d1[0], d1[1]]
elif d2[2] == minimum:
return [d2[0], d2[1]]
elif d3[2] == minimum:
return [d3[0], d3[1]]
elif d4[2] == minimum:
return [d4[0], d4[1]]

i=1
while flag:
d1 = newDistance(startingPoint[0]+increment, startingPoint[1], point1, point2, point3, point4)
d2 = newDistance(startingPoint[0]-increment, startingPoint[1], point1, point2, point3, point4)
d3 = newDistance(startingPoint[0], startingPoint[1]+increment, point1, point2, point3, point4)
d4 = newDistance(startingPoint[0], startingPoint[1]-increment, point1, point2, point3, point4)
print(i,' ', round(startingPoint[0], 2), round(startingPoint[1], 2))
minimum = min(d1[2], d2[2], d3[2], d4[2])
if minimum < minDistance:
startingPoint = newPoints(minimum, d1, d2, d3, d4)
minDistance = minimum
#print i,' ', round(startingPoint[0], 2), round(startingPoint[1], 2)
i+=1
else:
flag = False

OUT put
Min-Max and Alpha beta pruning

import math

def minimax(curDepth, nodeIndex,


maxTurn, scores,
targetDepth):
# base case : targetDepth reached
if (curDepth == targetDepth):
return scores[nodeIndex]

if (maxTurn):
return max(minimax(curDepth + 1, nodeIndex * 2,
False, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
False, scores, targetDepth))

else:
return min(minimax(curDepth + 1, nodeIndex * 2,
True, scores, targetDepth),
minimax(curDepth + 1, nodeIndex * 2 + 1,
True, scores, targetDepth))

# Driver code

scores=[]
#scores = [3, 5, 2, 9, 12, 5, 23, 23]
n=int(input("Enter value for range "))
for i in range(n):
x=int(input())
scores.append(x)

treeDepth = math.log(len(scores), n)

print("The optimal value is : ", end="")


print(minimax(0, 0, True, scores, treeDepth))
Iterative deepening search

from collections import defaultdict

class Graph:

def __init__(self,vertices):

# No. of vertices
self.V = vertices

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self,u,v):
self.graph[u].append(v)

# A function to perform a Depth-Limited search


# from given source 'src'
def DLS(self,src,target,maxDepth):

if src == target : return True

# If reached the maximum depth, stop recursing.


if maxDepth <= 0 : return False

for i in self.graph[src]:
if(self.DLS(i,target,maxDepth-1)):
return True
return False

def IDDFS(self,src, target, maxDepth):


for i in range(maxDepth):
if (self.DLS(src, target, i)):
return True
return False

g=Graph(7);
j=int(input("enter value for range "))
for i in range(j):

b=int(input("enter first edge "))


c=int(input("Enter second edge "))
g.addEdge(b, c)

target=int(input("Enter target Value : "))


maxDepth=int(input("Enter maximum Depth : "))
src=int(input("Enter source Value : "))
if g.IDDFS(src, target, maxDepth) == True:
print ("Target is reachable from source " +
"within max depth")
else :
print ("Target is NOT reachable from source " +
"within max depth")

A-star Algorithm

# Enter your code here. Read input from STDIN. Print output to STDOUT
class Node:
def __init__(self,value,point):
self.value = value
self.point = point
self.parent = None
self.H = 0
self.G = 0
def move_cost(self,other):
return 0 if self.value == '.' else 1

def children(point,grid):
x,y = point.point
links = [grid[d[0]][d[1]] for d in [(x-1, y),(x,y - 1),(x,y + 1),(x+1,y)]]
return [link for link in links if link.value != '%']
def manhattan(point,point2):
return abs(point.point[0] - point2.point[0]) + abs(point.point[1]-point2.point[0])
def aStar(start, goal, grid):
#The open and closed sets
openset = set()
closedset = set()
#Current point is the starting point
current = start
#Add the starting point to the open set
openset.add(current)
#While the open set is not empty
while openset:
#Find the item in the open set with the lowest G + H score
current = min(openset, key=lambda o:o.G + o.H)
#If it is the item we want, retrace the path and return it
if current == goal:
path = []
while current.parent:
path.append(current)
current = current.parent
path.append(current)
return path[::-1]
#Remove the item from the open set
openset.remove(current)
#Add it to the closed set
closedset.add(current)
#Loop through the node's children/siblings
for node in children(current,grid):
#If it is already in the closed set, skip it
if node in closedset:
continue
#Otherwise if it is already in the open set
if node in openset:
#Check if we beat the G score
new_g = current.G + current.move_cost(node)
if node.G > new_g:
#If so, update the node to have a new parent
node.G = new_g
node.parent = current
else:
#If it isn't in the open set, calculate the G and H score for the node
node.G = current.G + current.move_cost(node)
node.H = manhattan(node, goal)
#Set the parent to our current item
node.parent = current
#Add it to the set
openset.add(node)
#Throw an exception if there is no path
raise ValueError('No Path Found')
def next_move(pacman,food,grid):
#Convert all the points to instances of Node
for x in xrange(len(grid)):
for y in xrange(len(grid[x])):
grid[x][y] = Node(grid[x][y],(x,y))
#Get the path
path = aStar(grid[pacman[0]][pacman[1]],grid[food[0]][food[1]],grid)
#Output the path
printlen(path) - 1
for node in path:
x, y = node.point
printx, y
pacman_x, pacman_y = [ int(i) for i in input().strip().split() ]
food_x, food_y = [ int(i) for i in raw_input().strip().split() ]
x,y = [ int(i) for i in input().strip().split() ]

grid = []
for i in xrange(0, x):
grid.append(list(raw_input().strip()))

next_move((pacman_x, pacman_y),(food_x, food_y), grid)

OUTPUT

Potrebbero piacerti anche