How to use makeState method in avocado

Best Python code snippet using avocado_python

nkhetan-hw5.py

Source:nkhetan-hw5.py Github

copy

Full Screen

...192 successors.append(succ)193 return successors194 195# Create state from initial and goal state196def makeState(nw, n, ne, w, c, e, sw, s, se):197 statelist = [nw, n, ne, w, c, e, sw, s, se]198 for i in range(len(statelist)):199 # Replace blank with 0200 if statelist[i] == "blank":201 statelist[i] = 0202 return statelist203 204205def testInformedSearch(initialState, goalState, limit):206 '''print "\nHueristic: No of mispalced Tiles"207 t1 = time.time()208 informedSearch ([initialState], limit, 0, "one")209 print "Time taken for Informed Search(Misplaced Tiles): ", (time.time()-t1) ," Seconds"210 print "\nHueristic: Manhatten Distance"'''211 t2 = time.time()212 informedSearch ([initialState], limit, 0, "two")213 print "Time taken for Informed Search(Manhatten Distance): ", (time.time()-t2) ," Seconds"214 return215216217'''---------------------------------------------------------------------------------------------------------------------------'''218'''-----------------------------------------------------CODE FOR CBR----------------------------------------------------------'''219'''---------------------------------------------------------------------------------------------------------------------------'''220'''New code added here for Case Based Reasoning: @author: Nihar Khetan'''221222223def getPositionInGoalState(valueOfElement, gstate):224 '''It returns the position of a particular number which is in initial state, in Goal state225 number -> (number,number)'''226 for i in range(3):227 for j in range(3):228 if valueOfElement == gstate[i][j]:229 return (i,j)230231def calcEucledianDistance(initialState, gstate):232 '''It calculates Euclidean Distance for 8 Puzzle233 for an initialState Euclidean distance is the sum of moves for each number in initial state, to move it to the respective goal state234 so Heuristic Function 2 is based on Euclidean Distance235 initialState -> pathCost'''236 pathCost = 0237 for i in range(3):238 for j in range(3):239 if int(initialState[i][j]) != 0: 240 if int(initialState[i][j]) != int((gstate)[i][j]):241 x,y = getPositionInGoalState(initialState[i][j], gstate)242 pathCost = pathCost + (abs(x-i)+abs(y-j))243 return pathCost244245def convertToMatrice(state):246 '''converts the given state to a matrice like it looks for a 8- Puzzle'''247 count = 0248 newArr = [[" "," "," "],[" "," "," "],[" "," "," "]] 249 for i in range(3):250 for j in range(3): 251 newArr[i][j] = state[count]252 count+=1 253 return newArr254255def computeSimilarity(I0, I1, G1, G0):256 '''this function computes similarity between given initial and goal states to initial and goal states in case based database257 It uses sum of Manhattan distance : dist(I1-I0) + dist(G1, G0)258 where I0: given initial state I1: initial state from CBR database 259 G0: given goal state G1: goal state from CBR database260 '''261 scoreI0I1 = calcEucledianDistance(convertToMatrice(I0), convertToMatrice(I1)) 262 scoreG0G1 = calcEucledianDistance(convertToMatrice(G0), convertToMatrice(G1))263 264 return (scoreI0I1 + scoreG0G1)265266def getKeyForMostSimilar(I1, G1):267 ''' Gets the most similar case from case based reasoning and return the key for the same ''' 268 cbrDb = readFromDict()269 scoreDict = {}270 print ("++-------------------------------------+------------------- CBR Database -------------------+--------------------------------------++")271 print ("\tKey\t\t\t\tInitial State\t\t\t\tGoal State\t\t\t\tSimilarity Score ")272 for key in cbrDb.keys():273 scoreDict[key] = computeSimilarity(I1, cbrDb[key][0], cbrDb[key][len(cbrDb[key])-1], G1) 274 print ("\t%s\t\t\t\t%s\t\t%s\t\t%s " %(str(key), str(cbrDb[key][0]), str(cbrDb[key][len(cbrDb[key])-1]), str(computeSimilarity(I1, cbrDb[key][0], cbrDb[key][len(cbrDb[key])-1], G1))))275 return ((sorted(scoreDict.items(), key=lambda x:x[1]))[0][0], (sorted(scoreDict.items(), key=lambda x:x[1]))[0][1]) 276 277def getKey(initial, goal):278 ''' Gets the key form case based reasoning and returns the same for a given initial and goal states'''279 cbrDb = readFromDict()280 for key in cbrDb.keys():281 if ((cbrDb[key][0] == initial) and (cbrDb[key][len(cbrDb[key])-1] == goal)):282 return key283 return -1284 285def checkIfPresent(initial, goal):286 ''' Checks if initial and goal states are exactly present in the case based reasoning --> returns boolean'''287 cbrDB = readFromDict() 288 for eachProblem in cbrDB.values() : 289 if ((eachProblem[0] == initial) and (eachProblem[len(eachProblem)-1] == goal)):290 return True 291 return False 292293def checkIfPresentInAnyState(initial, goal):294 '''Function checks if given initial and goal exists in any of sub paths of solutions in CBR database295 list, list -> boolean'''296 cbrDB = readFromDict() 297 print ("Exact Match not found thus checking all states of all paths stored in CBR Database")298 299 for eachProblem in cbrDB.values() : 300 if ((initial in eachProblem) and (goal in eachProblem)):301 if (eachProblem.index(initial) < (eachProblem.index(goal))): 302 return True 303 else:304 return False 305 return False 306307def computePathFromAnyOtherState(initial, goal):308 '''Try to look at sub-paths of solutions in CBR database and if it is found returns the same 309 initial state, goal state --> list '''310 cbrDB = readFromDict() 311 counter = 0312 for eachProblem in cbrDB.values() : 313 if ((initial in eachProblem) and (goal in eachProblem)):314 if (eachProblem.index(initial) < (eachProblem.index(goal))):315 print ("MATCH FOUND in a path for Case Based Reasoning Database")316 print ("Key for case matched : " + str(counter)) 317 print ("Similarity Score = 0\n") 318 return eachProblem[eachProblem.index(initial):eachProblem.index(goal)+1] 319 else:320 return []321 counter += 1322 return [] 323324def readFromDict():325 '''Reader to read the cases stored in case based reasoning and returns the dictionery326 ---> returns a dictionery'''327 with open('cbr_database.pickle', 'rb') as handle:328 savedCases = pickle.load(handle)329 return savedCases330331def writeToDict(caseToWrite):332 '''Opens the case bases reasoning and write a new case to it, while persisting the older ones333 ---> does not return anything'''334 current = readFromDict()335 current.update(caseToWrite)336 with open('cbr_database.pickle', 'wb') as handle:337 pickle.dump(current, handle)338 return339340 341342def testCaseBasedSearch(listOfProblems): 343 '''Function which goes through each problem in list of problems and solves it using Case Based Search''' 344 345 for i in range(len(listOfProblems)): 346 initial1 = listOfProblems[i][0]347 goal1 = listOfProblems[i][1]348 global goalState349 print ("++---------------------------------------------------------------------------------------------------------------------------------------------++")350 print ("++---------------------------------------------------------------------------------------------------------------------------------------------++\n")351 352 print("Solving Problem : " + str(i+1))353 print("Given Initial State : " + str(initial1))354 print("Given Goal State : " + str(goal1) + "\n")355 '''If CBR database is empty solve the first problem and store it'''356 cbrCheck = readFromDict();357 if (cbrCheck == {}):358 print("+-+- Empty CBR Database Solving from scratch -+-+")359 goalState = goal1360 pathSearched = informedSearch ([initial1], 20000, 0, "two")361 outputProcedure(pathSearched)362 print("++-----Appending new Path to CBR Database------++\n")363 cbrDB = readFromDict()364 dictToAppend = {0:pathSearched}365 writeToDict(dictToAppend) 366 367 else:368 '''Case to check if initial state and goal state matches exactly :: BEST CASE''' 369 if (checkIfPresent(initial1,goal1)): 370 key = getKey(initial1,goal1)371 372 goalState = goal1373 print ("Exact Match Found in CBR at Key : " + str(key))374 print ("\tSimilarity Score = 0\n") 375 outputProcedure(readFromDict()[key])376 elif (checkIfPresentInAnyState(initial1, goal1) == True): 377 outputProcedure(computePathFromAnyOtherState(initial1, goal1))378 else:379 print ("\nInitial State and Goal State not found in sub paths hence computing SIMILARITY SCORES ::")380 (key, score) = getKeyForMostSimilar(initial1,goal1)381 382 if (score < 9):383 #use case based reasoning384 print ("\nScore less than THRESHOLD thus applying CBR")385 print ("\tMost Similar Key : " + str(key) + "\tSimilarity Score : " + str(score))386 cbrDB = readFromDict()387 #goal state is I0388 389 goalState = cbrDB[key][0]390 391 pathSearchedI0toI1 = informedSearch ([initial1], 20000, 0, "two")392 print("\tPath From I0 to I1 : " + str(pathSearchedI0toI1))393 pathSearchedI1toG1 = cbrDB[key]394 print("\tPath From I1 to G1 (CBR) : " + str(pathSearchedI1toG1)) 395 goalState = goal1396 pathSearchedG1toG0 = informedSearch ([cbrDB[key][len(cbrDB[key])-1]], 20000, 0, "two")397 print("\tPath From G1 to G0 : " + str(pathSearchedG1toG0)) 398 pathSearched = pathSearchedI0toI1 + pathSearchedI1toG1[1:-1] + pathSearchedG1toG0399 print("\nCombined Path I0 --> I1 --> G1 --> G0") 400 outputProcedure(pathSearched)401 print("++-----Appending new Path to CBR Database------++\n")402 dictToAppend = {(cbrDB.keys()[len(cbrDB.keys())-1]+1):pathSearched}403 writeToDict(dictToAppend)404 else:405 #find solution from scratch and add it to Case Based Reasoning Database406 print ("\nComputed Score : " + str(score) + ", Which is Greater than THRESHOLD : 8") 407 print("Solving from scratch using A* Search\n")408 goalState = goal1409 pathSearched = informedSearch ([initial1], 20000, 0, "two")410 outputProcedure(pathSearched)411 print("++-----Appending new Path to CBR Database------++\n")412 cbrDB = readFromDict() 413 if (cbrDB.keys() == []):414 dictToAppend = {0:pathSearched}415 writeToDict(dictToAppend) 416 else:417 dictToAppend = {(cbrDB.keys()[len(cbrDB.keys())-1]+1):pathSearched}418 writeToDict(dictToAppend) 419 420 421422def generateTestProblems(listOfProblems):423 '''This function generated a set of Random Problems.424 I have followed approach 1 where I give a predefined set of problems as input425 so this acts as a dummy function'''426427 testCaseBasedSearch(listOfProblems)428 429# Main()430if __name__ == "__main__":431 global goalState432 goalState = []433 print "<<<< :::::: CASE BASED REASONING TO SOLVE 8 PUZZLE :::::: >>>>\n"434 try:435 with open('cbr_database.pickle', 'rb') as handle:436 savedCases = pickle.load(handle)437 print ("printing the CBR Database")438 for eachKey in savedCases.keys():439 print (str(eachKey) + " : " + str(savedCases[eachKey])) 440 print("")441 except IOError: 442 emptyDict = {}443 with open('cbr_database.pickle', 'wb') as handle:444 pickle.dump(emptyDict, handle)445 446 447 '''Given sample list of problems'''448 listOfProblems = [449 [makeState("blank", 5, 3, 2, 1, 6, 4, 7, 8), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],450 [makeState("blank", 3, 6, 5, 7, 8, 2, 1, 4), makeState(1, 2, 3, 4, 5, 6, 7, "blank", 8)],451 [makeState(3, 6, "blank", 5, 7, 8, 2, 1, 4), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],452 [makeState("blank", 2, 5, 3, 1, 6, 4, 7, 8), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],453 [makeState(3, 2, 5, "blank", 1, 6, 4, 7, 8), makeState(1, "blank", 3, 4, 2, 5, 7, 8, 6)],454 [makeState("blank", 2, 1, 5, 3, 6, 4, 7, 8), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],455 [makeState(2, 5, "blank", 4, 6, 3, 7, 1, 8), makeState(1, 2, 3, 4, 5, 6, 7, "blank", 8)],456 [makeState(2, 6, 5, 4, "blank", 3, 7, 1, 8), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],457 [makeState(1, "blank", 3, 5, 2, 6, 4, 7, 8), makeState(1, 2, 3, 4, 8, 5, 7, "blank", 6)],458 [makeState("blank", 2, 3, 1, 5, 6, 4, 7, 8), makeState(2, 6, 5, 4, "blank", 3, 7, 1, 8)],459 [makeState(2, 3, 8, 1, 6, 5, 4, 7, "blank"), makeState("blank", 2, 3, 1, 5, 6, 4, 7, 8)],460 [makeState(2, 5, 3, 4, "blank", 8, 6, 1, 7), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],461 [makeState(3, 8, 5, 1, 6, 7, 4, 2, "blank"), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],462 [makeState(3, 8, 5, 1, "blank", 6, 4, 2, 7), makeState(1, 2, 3, 4, "blank", 5, 7, 8, 6)],463 [makeState(3, 8, 5, 1, 6, "blank", 4, 2, 7), makeState(1, 2, 3, 4, 8, 5, "blank", 7, 6)],464 [makeState(1, 3, 5, "blank", 8, 6, 4, 2, 7), makeState(1, 2, 3, 4, 5, "blank", 7, 8, 6)],465 [makeState(3, 8, 5, 1, 6, "blank", 4, 2, 7), makeState(1, 2, 3, 4, 8, 5, 7, "blank", 6)],466 [makeState("blank", 3, 5, 1, 8, 6, 4, 2, 7), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],467 [makeState("blank", 3, 5, 1, 8, 6, 4, 2, 7), makeState(1, 2, 3, 4, 5, 6, 7, 8, "blank")],468 [makeState(2, 5, 3, 4, "blank", 8, 6, 1, 7), makeState(1, 2, 3, 4, 5, 6, "blank", 7, 8)]469 ]470 t1 = time.time()471 generateTestProblems(listOfProblems)472 t2 = time.time()473 print "\n\nTime taken for solving by CBR: ", (t2-t1), " Seconds"474 ...

Full Screen

Full Screen

dataCollector.py

Source:dataCollector.py Github

copy

Full Screen

...65 #write result to file66 logFile.writerow([index+1,searchCost,level,timeDiff,limit])67def main():68 69 goalState = makeState(1,2,3,4,5,6,7,8,'blank') 70 # First group of test cases - should have solutions with depth <= 571 initialState1 = makeState(2, "blank", 3, 1, 5, 6, 4, 7, 8)72 initialState2 = makeState(1, 2, 3, "blank", 4, 6, 7, 5, 8)73 initialState3 = makeState(1, 2, 3, 4, 5, 6, 7, "blank", 8)74 initialState4 = makeState(1, "blank", 3, 5, 2, 6, 4, 7, 8)75 initialState5 = makeState(1, 2, 3, 4, 8, 5, 7, "blank", 6)76 # Second group of test cases - should have solutions with depth <= 1077 initialState6 = makeState(2, 8, 3, 1, "blank", 5, 4, 7, 6)78 initialState7 = makeState(1, 2, 3, 4, 5, 6, "blank", 7, 8)79 initialState8 = makeState("blank", 2, 3, 1, 5, 6, 4, 7, 8)80 initialState9 = makeState(1, 3, "blank", 4, 2, 6, 7, 5, 8)81 initialState10 = makeState(1, 3, "blank", 4, 2, 5, 7, 8, 6)82 # Third group of test cases - should have solutions with depth <= 2083 initialState11 = makeState("blank", 5, 3, 2, 1, 6, 4, 7, 8)84 initialState12 = makeState(5, 1, 3, 2, "blank", 6, 4, 7, 8)85 initialState13 = makeState(2, 3, 8, 1, 6, 5, 4, 7, "blank")86 initialState14 = makeState(1, 2, 3, 5, "blank", 6, 4, 7, 8)87 initialState15 = makeState("blank", 3, 6, 2, 1, 5, 4, 7, 8)88 # Fourth group of test cases - should have solutions with depth <= 5089 initialState16 = makeState(2, 6, 5, 4, "blank", 3, 7, 1, 8)90 initialState17 = makeState(3, 6, "blank", 5, 7, 8, 2, 1, 4)91 initialState18 = makeState(1, 5, "blank", 2, 3, 8, 4, 6, 7)92 initialState19 = makeState(2, 5, 3, 4, "blank", 8, 6, 1, 7)93 initialState20 = makeState(3, 8, 5, 1, 6, 7, 4, 2, "blank")94 testcases = [initialState1,initialState2,initialState3,initialState4,initialState5,initialState6,initialState7,initialState8,initialState9,initialState10,initialState11,initialState12,initialState13,initialState14,initialState15,initialState16,initialState17,initialState18,initialState19,initialState20]95 #executeTestCases(testcases[0:20],goalState,SearchMethod.CELL_DIFF)96 #executeTestCases(testcases[0:20],goalState,SearchMethod.MANHATTAN)97 #executeTestCases(testcases[0:20],goalState,SearchMethod.BFS)98if __name__ == "__main__":...

Full Screen

Full Screen

tester.py

Source:tester.py Github

copy

Full Screen

...6import time7"""8from armajrik_uninformed import makeState9from armajrik_uninformed import testUninformedSearch10goalState = makeState(1,2,3,4,5,6,7,8,'blank') 11# First group of test cases - should have solutions with depth <= 512initialState1 = makeState(2, "blank", 3, 1, 5, 6, 4, 7, 8)13initialState2 = makeState(1, 2, 3, "blank", 4, 6, 7, 5, 8)14initialState3 = makeState(1, 2, 3, 4, 5, 6, 7, "blank", 8)15initialState4 = makeState(1, "blank", 3, 5, 2, 6, 4, 7, 8)16initialState5 = makeState(1, 2, 3, 4, 8, 5, 7, "blank", 6)17# Second group of test cases - should have solutions with depth <= 1018initialState6 = makeState(2, 8, 3, 1, "blank", 5, 4, 7, 6)19initialState7 = makeState(1, 2, 3, 4, 5, 6, "blank", 7, 8)20initialState8 = makeState("blank", 2, 3, 1, 5, 6, 4, 7, 8)21initialState9 = makeState(1, 3, "blank", 4, 2, 6, 7, 5, 8)22initialState10 = makeState(1, 3, "blank", 4, 2, 5, 7, 8, 6)23# Third group of test cases - should have solutions with depth <= 2024initialState11 = makeState("blank", 5, 3, 2, 1, 6, 4, 7, 8)25initialState12 = makeState(5, 1, 3, 2, "blank", 6, 4, 7, 8)26initialState13 = makeState(2, 3, 8, 1, 6, 5, 4, 7, "blank")27initialState14 = makeState(1, 2, 3, 5, "blank", 6, 4, 7, 8)28initialState15 = makeState("blank", 3, 6, 2, 1, 5, 4, 7, 8)29# Fourth group of test cases - should have solutions with depth <= 5030initialState16 = makeState(2, 6, 5, 4, "blank", 3, 7, 1, 8)31initialState17 = makeState(3, 6, "blank", 5, 7, 8, 2, 1, 4)32initialState18 = makeState(1, 5, "blank", 2, 3, 8, 4, 6, 7)33initialState19 = makeState(2, 5, 3, 4, "blank", 8, 6, 1, 7)34initialState20 = makeState(3, 8, 5, 1, 6, 7, 4, 2, "blank")35initialState = initialState1336#testInformedSearchTwo(initialState,goalState,2000)37#raw_input()38#testInformedSearchOne(initialState,goalState,5000)39#raw_input()40testUninformedSearch(initialState,goalState,3500)41#testInformedSearch(initialState,goalState,2000)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful