from time import time from queue import Queue #%% [code] #Creating a class Puzzle class Puzzle: #Setting the goal state of 8-puzzle goal_state=[1,2,3,8,0,4,7,6,5] num_of_instances=0 #constructor to initialize the class members def _init_(self,state,parent,action): self.parent=parent self.state=state self.action=action #TODO: incrementing the number of instance by 1 Puzzle.num_of_instances+= 1 #function used to display a state of 8-puzzle def _str_(self): return str(self.state[0:3])+'\n'+str(self.state[3:6])+'\n'+str(self.state[6:9]) #method to compare the current state with the goal state def goal_test(self): #TODO: include a condition to compare the current state with the goal state if self.state == Puzzle.goal_state : return True return False #static method to find the legal action based on the current board position @staticmethod def find_legal_actions(i,j): legal_action = ['U', 'D', 'L', 'R'] if i == 0: # if row is 0 in board then up is disable legal_action.remove('U') elif i == 2: #TODO: down is disable legal_action.remove('D') if j == 0: #TODO: Left is disable legal_action.remove('L') elif j == 2: #TODO: Right is disable legal_action.remove('R') return legal_action #method to generate the child of the current state of the board def generate_child(self): #TODO: create an empty list children=[] x = self.state.index(0) i = int(x / 3) j = int(x % 3) #TODO: call the method to find the legal actions based on i and j values legal_actions= Puzzle.find_legal_actions(i,j) #TODO:Iterate over all legal actions for action in legal_actions: new_state = self.state.copy() #if the legal action is UP if action is 'U': #Swapping between current index of 0 with its up element on the board new_state[x], new_state[x-3] = new_state[x-3], new_state[x] elif action is 'D': #TODO: Swapping between current index of 0 with its down element on the board new_state[x], new_state[x+3] = new_state[x+3],new_state[x] elif action is 'L': #TODO: Swapping between the current index of 0 with its left element on the board new_state[x], new_state[x-1] = new_state[x-1],new_state[x] elif action is 'R': #TODO: Swapping between the current index of 0 with its right element on the board new_state[x], new_state[x+1] = new_state[x+1],new_state[x] children.append(Puzzle(new_state,self,action)) #TODO: return the children return children #method to find the solution def find_solution(self): solution = [] solution.append(self.action) path = self while path.parent != None: path = path.parent solution.append(path.action) solution = solution[:-1] solution.reverse() return solution #%% [code] #method for breadth first search #TODO: pass the initial_state as parameter to the breadth_first_search method def breadth_first_search(initial_state): start_node = Puzzle(initial_state, None, None) print("Initial state:") print(start_node) if start_node.goal_test(): return start_node.find_solution() q = Queue() #TODO: put start_node into the Queue q.put(start_node) #TODO: create an empty list of explored nodes explored=[] #TODO: Iterate the queue until empty. Use the empty() method of Queue while not(q.empty()): #TODO: get the current node of a queue. Use the get() method of Queue node=q.get() #TODO: Append the state of node in the explored list as node.state explored.append(node.state) #TODO: call the generate_child method to generate the child nodes of current node children=Puzzle.generate_child(node) #TODO: Iterate over each child node in children for child in children: if child.state not in explored: if child.goal_test(): return child.find_solution() q.put(child) return #%% [code] #Start executing the 8-puzzle with setting up the initial state #Here we have considered 3 initial state intitalized using state variable state=[[1, 3, 4, 8, 6, 2, 7, 0, 5], [2, 8, 1, 0, 4, 3, 7, 6, 5], [2, 8, 1, 4, 6, 3, 0, 7, 5]] #Iterate over number of initial_state for i in range(0,3): #TODO: Initialize the num_of_instances to zero Puzzle.num_of_instances=0 #Set t0 to current time t0=time() bfs= breadth_first_search(state[i]) #Get the time t1 after executing the breadth_first_search method t1=time()-t0 print('BFS:', bfs) print('space:',Puzzle.num_of_instances) print('time:',t1) print() print('------------------------------------------')
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |