Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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
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
'''
@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)]
prob = random.random()
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 = []
if population[0].fitness <= 0:
found = True
break
population = new_generation
generation += 1
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 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
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
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)
class Graph:
def __init__(self,vertices):
# No. of vertices
self.V = vertices
for i in self.graph[src]:
if(self.DLS(i,target,maxDepth-1)):
return True
return False
g=Graph(7);
j=int(input("enter value for range "))
for i in range(j):
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()))
OUTPUT