SlideShare a Scribd company logo
1 of 2
Download to read offline
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

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

Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docxLiterary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
jeremylockett77
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
mail931892
 
Will upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdfWill upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdf
sales223546
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
eyewaregallery
 
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2).docx
Mylib.pydef allInOne(n1, n2)    return {addplus(n1, n2).docxMylib.pydef allInOne(n1, n2)    return {addplus(n1, n2).docx
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2).docx
roushhsiu
 
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2.docx
Mylib.pydef allInOne(n1, n2)    return {addplus(n1, n2.docxMylib.pydef allInOne(n1, n2)    return {addplus(n1, n2.docx
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2.docx
gemaherd
 

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

Formal methods
Formal methods Formal methods
Formal methods
 
Functional programming with clojure
Functional programming with clojureFunctional programming with clojure
Functional programming with clojure
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185
 
cs8project
cs8projectcs8project
cs8project
 
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docxLiterary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
Literary Genre MatrixPart 1 Matrix FictionNon-fiction.docx
 
Matlab project
Matlab projectMatlab project
Matlab project
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
Help I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdfHelp I keep getting the same error when running a code. Below is the.pdf
Help I keep getting the same error when running a code. Below is the.pdf
 
Trident International Graphics Workshop 2014 5/5
Trident International Graphics Workshop 2014 5/5Trident International Graphics Workshop 2014 5/5
Trident International Graphics Workshop 2014 5/5
 
Will upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdfWill upvote asapPlease help my code gives me incorrect val.pdf
Will upvote asapPlease help my code gives me incorrect val.pdf
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212The Ring programming language version 1.10 book - Part 71 of 212
The Ring programming language version 1.10 book - Part 71 of 212
 
Monadologie
MonadologieMonadologie
Monadologie
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdfLab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
Lab Assignment 17 - Working with Object ArraysIn the old days we w.pdf
 
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2).docx
Mylib.pydef allInOne(n1, n2)    return {addplus(n1, n2).docxMylib.pydef allInOne(n1, n2)    return {addplus(n1, n2).docx
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2).docx
 
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2.docx
Mylib.pydef allInOne(n1, n2)    return {addplus(n1, n2.docxMylib.pydef allInOne(n1, n2)    return {addplus(n1, n2.docx
Mylib.pydef allInOne(n1, n2) return {addplus(n1, n2.docx
 

More from aashisha5

Caso de estudio Terror en el Taj Bombay liderazgo centrado.pdf
Caso de estudio  Terror en el Taj Bombay liderazgo centrado.pdfCaso de estudio  Terror en el Taj Bombay liderazgo centrado.pdf
Caso de estudio Terror en el Taj Bombay liderazgo centrado.pdf
aashisha5
 
Bonnie Morgen primer da de trabajo y un dilema tico INTR.pdf
Bonnie Morgen primer da de trabajo y un dilema tico  INTR.pdfBonnie Morgen primer da de trabajo y un dilema tico  INTR.pdf
Bonnie Morgen primer da de trabajo y un dilema tico INTR.pdf
aashisha5
 
C++ Please test your program before you submit the answer.pdf
C++ Please test your program before you submit the answer.pdfC++ Please test your program before you submit the answer.pdf
C++ Please test your program before you submit the answer.pdf
aashisha5
 

More from aashisha5 (20)

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

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 

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)