Best Python code snippet using lisa_python
search.py
Source:search.py  
1# search.py2# ---------3# Licensing Information:  You are free to use or extend these projects for4# educational purposes provided that (1) you do not distribute or publish5# solutions, (2) you retain this notice, and (3) you provide clear6# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.7# 8# Attribution Information: The Pacman AI projects were developed at UC Berkeley.9# The core projects and autograders were primarily created by John DeNero10# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).11# Student side autograding was added by Brad Miller, Nick Hay, and12# Pieter Abbeel (pabbeel@cs.berkeley.edu).13"""14In search.py, you will implement generic search algorithms which are called by15Pacman agents (in searchAgents.py).16"""17import util18class SearchProblem:19    """20    This class outlines the structure of a search problem, but doesn't implement21    any of the methods (in object-oriented terminology: an abstract class).22    You do not need to change anything in this class, ever.23    """24    def getStartState(self):25        """26        Returns the start state for the search problem.27        """28        util.raiseNotDefined()29    def isGoalState(self, state):30        """31          state: Search state32        Returns True if and only if the state is a valid goal state.33        """34        util.raiseNotDefined()35    def getSuccessors(self, state):36        """37          state: Search state38        For a given state, this should return a list of triples, (successor,39        action, stepCost), where 'successor' is a successor to the current40        state, 'action' is the action required to get there, and 'stepCost' is41        the incremental cost of expanding to that successor.42        """43        util.raiseNotDefined()44    def getCostOfActions(self, actions):45        """46         actions: A list of actions to take47        This method returns the total cost of a particular sequence of actions.48        The sequence must be composed of legal moves.49        """50        util.raiseNotDefined()51def tinyMazeSearch(problem):52    """53    Returns a sequence of moves that solves tinyMaze.  For any other maze, the54    sequence of moves will be incorrect, so only use this for tinyMaze.55    """56    from game import Directions57    s = Directions.SOUTH58    w = Directions.WEST59    return [s, s, w, s, w, w, s, w]60def depthFirstSearch(problem):61    """62    Search the deepest nodes in the search tree first.63    Your search algorithm needs to return a list of actions that reaches the64    goal. Make sure to implement a graph search algorithm.65    To get started, you might want to try some of these simple commands to66    understand the search problem that is being passed in:67    print "Start:", problem.getStartState()68    print "Is the start a goal?", problem.isGoalState(problem.getStartState())69    print "Start's successors:", problem.getSuccessors(problem.getStartState())70    """71    "*** YOUR CODE HERE ***"72    state_stack = util.Stack()73    set_states = set()74    state_stack.push((problem.getStartState(), []))75    while not state_stack.isEmpty():76        popped_state, popped_moves = state_stack.pop()77        if (popped_state in set_states):78            continue79        elif problem.isGoalState(popped_state):80            return popped_moves81        set_states.add(popped_state)82        for state, direction, cost in problem.getSuccessors(popped_state):83            if (state in set_states):84                continue85            state_stack.push((state, popped_moves + [direction]))86    return []87def breadthFirstSearch(problem):88    """Search the shallowest nodes in the search tree first."""89    "*** YOUR CODE HERE ***"90    state_queue = util.Queue()91    set_states = set()92    state_queue.push((problem.getStartState(), []))93    while not state_queue.isEmpty():94        popped_state, popped_moves = state_queue.pop()95        if (popped_state in set_states):96            continue97        elif problem.isGoalState(popped_state):98            return popped_moves99        set_states.add(popped_state)100        for state, direction, cost in problem.getSuccessors(popped_state):101            if (state in set_states):102                continue103            state_queue.push((state, popped_moves + [direction]))104    return []105def uniformCostSearch(problem):106    """Search the node of least total cost first."""107    "*** YOUR CODE HERE ***"108    state_pq = util.PriorityQueue()109    set_states = set()110    state_pq.push((problem.getStartState(), [], 0), 0)111    while not state_pq.isEmpty():112        popped_state, popped_moves, popped_cost = state_pq.pop()113        if (popped_state in set_states):114            continue115        elif problem.isGoalState(popped_state):116            return popped_moves117        set_states.add(popped_state)118        for state, direction, cost in problem.getSuccessors(popped_state):119            if (state in set_states):120                continue121            state_pq.push((state, popped_moves + [direction], popped_cost + cost), popped_cost + cost)122    return []123def nullHeuristic(state, problem=None):124    """125    A heuristic function estimates the cost from the current state to the nearest126    goal in the provided SearchProblem.  This heuristic is trivial.127    """128    return 0129def aStarSearch(problem, heuristic=nullHeuristic):130    """Search the node that has the lowest combined cost and heuristic first."""131    "*** YOUR CODE HERE ***"132    state_pq = util.PriorityQueue()133    set_states = set()134    state_pq.push((problem.getStartState(), [], 0), 0)135    while not state_pq.isEmpty():136        popped_state, popped_moves, popped_cost = state_pq.pop()137        if (popped_state in set_states):138            continue139        if problem.isGoalState(popped_state):140            return popped_moves141        set_states.add(popped_state)142        for state, direction, cost in problem.getSuccessors(popped_state):143            if (state in set_states):144                continue145            hvalue = heuristic(state, problem)146            state_pq.push((state, popped_moves + [direction], popped_cost + cost), popped_cost + cost + hvalue)147    return []148# Abbreviations149bfs = breadthFirstSearch150dfs = depthFirstSearch151astar = aStarSearch...main.py
Source:main.py  
...34		d_ndfa['Transitions'][state] = {} 35	for each in lines_trans:36		d_ndfa['Transitions'][each[0]][each[1]] = each[2:] 37	print(d_ndfa)38def print_set_states(set_states):39	print("\nTransition of Set of States\n".center(20))40	for sets in set_states:41		for transition in set_states[sets]:42			print(sets,",",transition, "=>", set_states[sets][transition], "\n")43def equivalence(set_states):44	i = 045	d_dfa={}46	d_eq={}47	for sets in set_states:48		d_eq[sets] = "q"+str(i) 49		d_dfa['q'+str(i)] = set_states[sets] 50		i+=151	for key in d_dfa: 52		for letter, trans in d_dfa[key].items():53			key_name = ",".join(trans)54			if key_name in d_eq.keys(): 55				d_dfa[key][letter] = d_eq[key_name] 56	return d_dfa57def print_table(set_states, alphabet):58	print("Dfa transition table\n".center(25))59	table = PrettyTable()60	header = ['States']+alphabet61	table.field_names = header62	for s in set_states:63		row_data = []64		row_data.append(s)65		for t in alphabet:66			if t in set_states[s]:67				row_data.append(set_states[s][t])68			else:69				row_data.append("--")70			if len(row_data) == len(header):71				table.add_row(row_data)72	print(table)73def main():74	d_ndfa = read_data()75	result = to_dfa(d_ndfa['Initial_state'], d_ndfa, set_states = {})76	print_set_states(result)77	print_table(result, d_ndfa['Alphabet'])78	print_table(equivalence(result), d_ndfa['Alphabet'])79if __name__ == "__main__":...utils.py
Source:utils.py  
1"""2MIT License, Kemal Ficici, 20183github.com/kemfic4"""5import numpy as np6import matplotlib7import matplotlib.pyplot as plt8class process(object):9    process_response = 010    def __init__(self, const_shift=0, noise=False):11        self.constant_shift = const_shift/512.012        self.noise = noise13    def update(self, controller_response, current_state):14        self.process_response = self.process_response*0.96 - 0.01*controller_response + self.constant_shift +self.noise*((np.random.rand()-0.5)/100)15        self.process_response = min(1, self.process_response)16        self.process_response = max(-1, self.process_response)17        return current_state + self.process_response18def error(current_state, set_state):19    return current_state - set_state20    21class Plant(object):22    23    def __init__(self, control, d_t=0.1, t_max=60, set_steady=False, set_shift=False, set_sin=False, noise=False):24        self.delta_t = d_t25        self.t_max = t_max26        self.t = np.arange(0, self.t_max, self.delta_t)27        if set_sin:28            self.set_states = np.sin(self.t*4*np.pi/self.t_max)29        elif set_steady:30            self.set_states = np.zeros_like(self.t)31        else:32            self.set_states = np.zeros_like(self.t)33            self.set_states[200:400] = 134        35        self.cur_process = process(set_shift, noise)        36        self.controller = control37    def simulate(self):38        states = np.zeros_like(self.t)39        states[0] = -140        errors = np.zeros_like(self.t)41        errors[0] = error(states[0], self.set_states[0])42        for i in range(1,len(self.t)):43            controller_response = self.controller.update(errors[i-1], delta_t = self.delta_t)44            states[i] = self.cur_process.update(controller_response, states[i-1])45            errors[i] = error(states[i], self.set_states[i])46        47        errortotal = np.sum(abs(errors))48        plt.plot(states, color='blue', label='environment state')49        plt.plot(self.set_states, color='red', label = 'set (desired) state')50        plt.plot([], color='none', label = 'total error: ' + str(errortotal)[0:9])51        plt.xlabel('Time')52        plt.ylabel('Error')53        plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
