SlideShare a Scribd company logo
I got this python coding for below quesion but i dont know how to run the code . i dont know how
the input should be please do help me out and provide me with some screenshots on how to run
the coding to refer thank you so much!!!
Write a program ( using any programming language) that implements A* algorithm for solving n-
puzzle problem (n<=20) that is a generalization for 8-puzzle problem.
propose and implement four different heuristics for this problem.
import heapq
import math
# Define a class for nodes in the search tree
class Node:
def __init__(self, state, parent=None, action=None, g=0, h=0):
self.state = state
self.parent = parent
self.action = action
self.g = g
self.h = h
def f(self):
return self.g + self.h
def __lt__(self, other):
return self.f() < other.f()
# Define a function to get the blank tile position in the puzzle
def find_blank(puzzle):
for i in range(len(puzzle)):
for j in range(len(puzzle)):
if puzzle[i][j] == 0:
return i, j
return None
# Define a function to get the successors of a node in the search tree
def get_successors(node):
successors = []
blank_i, blank_j = find_blank(node.state)
for action in ["up", "down", "left", "right"]:
new_i, new_j = blank_i, blank_j
if action == "up":
new_i -= 1
elif action == "down":
new_i += 1
elif action == "left":
new_j -= 1
elif action == "right":
new_j += 1
if 0 <= new_i < len(node.state) and 0 <= new_j < len(node.state):
new_state = [row[:] for row in node.state]
new_state[blank_i][blank_j], new_state[new_i][new_j] = new_state[new_i][new_j],
new_state[blank_i][blank_j]
successors.append(Node(new_state, node, action, node.g + 1, 0))
return successors
# Define a function to check if a state is the goal state
def is_goal(puzzle):
n = len(puzzle)
return all(puzzle[i][j] == i * n + j + 1 for i in range(n) for j in range(n - 1)) and puzzle[n - 1][n - 1] == 0
# Define a function to calculate the number of misplaced tiles heuristic
def num_misplaced_tiles(puzzle):
n = len(puzzle)
return sum(puzzle[i][j] != i * n + j + 1 for i in range(n) for j in range(n))
# Define a function to calculate the Manhattan distance heuristic
def manhattan_distance(puzzle):
n = len(puzzle)
distance = 0
for i in range(n):
for j in range(n):
if puzzle[i][j] != 0:
row = (puzzle[i][j] - 1) // n
col = (puzzle[i][j] - 1) % n
distance += abs(i - row) + abs(j - col)
return distance
# Define a function to calculate the Euclidean distance heuristic
def euclidean_distance(puzzle):
n = len(puzzle)
distance = 0
for i in range(n):
for j in range(n):
if puzzle[i][j] != 0:
row = (puzzle[i][j] - 1)

More Related Content

PDF
im solving tha m-puzzel sliding tail problem where m = n^2 - 1 I ha.pdf
PDF
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
PDF
Please help me fix this code! will upvote. The code needs to produce .pdf
PDF
Please help this code is supposed to evaluate current node state and i.pdf
PDF
Artificial Intelligence Practical Manual.pdf
PDF
Will upvote asapPlease help my code gives me incorrect val.pdf
PDF
19012011102_Nayan Oza_Practical-4_AI.pdf
PDF
# Imports# Include your imports here, if any are used. import.pdf
im solving tha m-puzzel sliding tail problem where m = n^2 - 1 I ha.pdf
goal_state = [1, 8, 7, 2, 0, 6, 3, 4, 5] #goal_state = [1, 0, 7, 2, .pdf
Please help me fix this code! will upvote. The code needs to produce .pdf
Please help this code is supposed to evaluate current node state and i.pdf
Artificial Intelligence Practical Manual.pdf
Will upvote asapPlease help my code gives me incorrect val.pdf
19012011102_Nayan Oza_Practical-4_AI.pdf
# Imports# Include your imports here, if any are used. import.pdf

Similar to I got this python coding for below quesion but i dont know h.pdf (20)

PDF
AI_Lab_File()[1]sachin_final (1).pdf
PDF
19012011102_Nayan Oza_Practical-5_AI.pdf
DOCX
Maze Solver - Rubric.xlsxSheet1Maze Solver - RubricStudent Nam.docx
PPTX
A Programmng Exercise in 40 characters or more
DOCX
python_assignmentHanoi (1).py################################.docx
PDF
Fix this code so that it will run with proper answers, please dont u.pdf
PDF
Will upvote Please fix the following code and post your inputs and o.pdf
PDF
AI-Programs.pdf
DOC
Programs.doc
PDF
Breadth-first search is a graph traversal algorithm
PDF
PDF
Shoot-for-A-Star
DOCX
New microsoft office word document
KEY
groovy & grails - lecture 8
PPTX
8 puzzle problem in PROLOG programming Language
PDF
What is the complete code for this problem- DON'T POST A MISSING CODE.pdf
PDF
Heuristic search
PPT
04 search heuristic
PPTX
Constraint propagation
PDF
AI & ML Lab Manual1_BCE.pdf artificial intelligence
AI_Lab_File()[1]sachin_final (1).pdf
19012011102_Nayan Oza_Practical-5_AI.pdf
Maze Solver - Rubric.xlsxSheet1Maze Solver - RubricStudent Nam.docx
A Programmng Exercise in 40 characters or more
python_assignmentHanoi (1).py################################.docx
Fix this code so that it will run with proper answers, please dont u.pdf
Will upvote Please fix the following code and post your inputs and o.pdf
AI-Programs.pdf
Programs.doc
Breadth-first search is a graph traversal algorithm
Shoot-for-A-Star
New microsoft office word document
groovy & grails - lecture 8
8 puzzle problem in PROLOG programming Language
What is the complete code for this problem- DON'T POST A MISSING CODE.pdf
Heuristic search
04 search heuristic
Constraint propagation
AI & ML Lab Manual1_BCE.pdf artificial intelligence
Ad

More from aashisha5 (20)

PDF
An economic model is useful only if it Group of answer choi.pdf
PDF
Caso de estudio Terror en el Taj Bombay liderazgo centrado.pdf
PDF
Caroline es una persona popular con un gran ego Se mete en .pdf
PDF
Bonnie Morgen primer da de trabajo y un dilema tico INTR.pdf
PDF
Answer the following a What is meant by the rounding unit.pdf
PDF
Are global teams necessary for a multinational corporation t.pdf
PDF
ABC company is expecting an ebit of rs 100000 whose equity .pdf
PDF
Aadaki sahne oyununu dnn ki periyotta tekrarlanr Oyuncu.pdf
PDF
A Question Briefly define what we mean by Uninsured B Q.pdf
PDF
assume your team is developing a WBS to renovate a dorm at y.pdf
PDF
5 Ha sido contratado como director de marketing de DoorDash.pdf
PDF
A Company is planning to undertake a project requiring initi.pdf
PDF
A cafetery carefully monitors customer orders and discovered.pdf
PDF
70 of all students at a college still need to take another .pdf
PDF
31 Soru metni Aadaki ifadelerden hangisi dorudur A Derin.pdf
PDF
353 Use multifactor authentication for local and network .pdf
PDF
Developing and developed economies use a range of industrial.pdf
PDF
A Laura y Len se les concedi el divorcio en 2019 De acuer.pdf
PDF
C++ Please test your program before you submit the answer.pdf
PDF
A veces una empresa antigua en una industria puede construi.pdf
An economic model is useful only if it Group of answer choi.pdf
Caso de estudio Terror en el Taj Bombay liderazgo centrado.pdf
Caroline es una persona popular con un gran ego Se mete en .pdf
Bonnie Morgen primer da de trabajo y un dilema tico INTR.pdf
Answer the following a What is meant by the rounding unit.pdf
Are global teams necessary for a multinational corporation t.pdf
ABC company is expecting an ebit of rs 100000 whose equity .pdf
Aadaki sahne oyununu dnn ki periyotta tekrarlanr Oyuncu.pdf
A Question Briefly define what we mean by Uninsured B Q.pdf
assume your team is developing a WBS to renovate a dorm at y.pdf
5 Ha sido contratado como director de marketing de DoorDash.pdf
A Company is planning to undertake a project requiring initi.pdf
A cafetery carefully monitors customer orders and discovered.pdf
70 of all students at a college still need to take another .pdf
31 Soru metni Aadaki ifadelerden hangisi dorudur A Derin.pdf
353 Use multifactor authentication for local and network .pdf
Developing and developed economies use a range of industrial.pdf
A Laura y Len se les concedi el divorcio en 2019 De acuer.pdf
C++ Please test your program before you submit the answer.pdf
A veces una empresa antigua en una industria puede construi.pdf
Ad

Recently uploaded (20)

PPTX
Lesson notes of climatology university.
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Institutional Correction lecture only . . .
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Complications of Minimal Access Surgery at WLH
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
Lesson notes of climatology university.
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
RMMM.pdf make it easy to upload and study
Institutional Correction lecture only . . .
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Complications of Minimal Access Surgery at WLH
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
102 student loan defaulters named and shamed – Is someone you know on the list?
Computing-Curriculum for Schools in Ghana
Pharmacology of Heart Failure /Pharmacotherapy of CHF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Renaissance Architecture: A Journey from Faith to Humanism
VCE English Exam - Section C Student Revision Booklet
Pharma ospi slides which help in ospi learning
Final Presentation General Medicine 03-08-2024.pptx
Supply Chain Operations Speaking Notes -ICLT Program
PPH.pptx obstetrics and gynecology in nursing

I got this python coding for below quesion but i dont know h.pdf

  • 1. I got this python coding for below quesion but i dont know how to run the code . i dont know how the input should be please do help me out and provide me with some screenshots on how to run the coding to refer thank you so much!!! Write a program ( using any programming language) that implements A* algorithm for solving n- puzzle problem (n<=20) that is a generalization for 8-puzzle problem. propose and implement four different heuristics for this problem. import heapq import math # Define a class for nodes in the search tree class Node: def __init__(self, state, parent=None, action=None, g=0, h=0): self.state = state self.parent = parent self.action = action self.g = g self.h = h def f(self): return self.g + self.h def __lt__(self, other): return self.f() < other.f() # Define a function to get the blank tile position in the puzzle def find_blank(puzzle): for i in range(len(puzzle)): for j in range(len(puzzle)): if puzzle[i][j] == 0: return i, j return None # Define a function to get the successors of a node in the search tree def get_successors(node): successors = [] blank_i, blank_j = find_blank(node.state) for action in ["up", "down", "left", "right"]: new_i, new_j = blank_i, blank_j if action == "up": new_i -= 1 elif action == "down": new_i += 1 elif action == "left": new_j -= 1 elif action == "right": new_j += 1 if 0 <= new_i < len(node.state) and 0 <= new_j < len(node.state):
  • 2. new_state = [row[:] for row in node.state] new_state[blank_i][blank_j], new_state[new_i][new_j] = new_state[new_i][new_j], new_state[blank_i][blank_j] successors.append(Node(new_state, node, action, node.g + 1, 0)) return successors # Define a function to check if a state is the goal state def is_goal(puzzle): n = len(puzzle) return all(puzzle[i][j] == i * n + j + 1 for i in range(n) for j in range(n - 1)) and puzzle[n - 1][n - 1] == 0 # Define a function to calculate the number of misplaced tiles heuristic def num_misplaced_tiles(puzzle): n = len(puzzle) return sum(puzzle[i][j] != i * n + j + 1 for i in range(n) for j in range(n)) # Define a function to calculate the Manhattan distance heuristic def manhattan_distance(puzzle): n = len(puzzle) distance = 0 for i in range(n): for j in range(n): if puzzle[i][j] != 0: row = (puzzle[i][j] - 1) // n col = (puzzle[i][j] - 1) % n distance += abs(i - row) + abs(j - col) return distance # Define a function to calculate the Euclidean distance heuristic def euclidean_distance(puzzle): n = len(puzzle) distance = 0 for i in range(n): for j in range(n): if puzzle[i][j] != 0: row = (puzzle[i][j] - 1)