Best Python code snippet using hypothesis
driver.py
Source:driver.py  
1import os2import sys3import numpy as np4import queue5from copy import deepcopy6from itertools import product7class Sudoku:8    def __init__(self, initial_config):9        self.board = np.asarray([int(i) for i in initial_config])10        # board = board.reshape(9, 9)11        self.rows = 'ABCDEFGHI'12        self.cols = '123456789'13        self.digits = '123456789'14        self.variables = {}15        # coordinates of cells in grid16        self.grid_coord = product(self.rows, self.cols)17        self.sudoku_board = dict(zip(self.grid_coord, self.board))18        self.rows_all_diff = [p for row in self.rows for p in product(row, self.cols)]19        self.cols_all_diff = [p for col in self.cols for p in product(self.rows, col)]20        self.block_add_diff = [p21                               for i in range(0, 9, 3)22                               for j in range(0, 9, 3)23                               for row in self.rows[i:i + 3]24                               for col in self.cols[j:j + 3]25                               for p in product(row, col)26                               ]27        self.tot_constr = set(self.rows_all_diff + self.cols_all_diff + self.block_add_diff)28        self.units = dict((pos, [u for u in self.tot_constr if u in self.tot_constr]) for pos in self.grid_coord)29class CSP:30    def __init__(self):31        self.V = {}32        self.D = {}33        self.C = {}34        self.A_partial = {}35        self.rows = 'ABCDEFGHI'36        self.cols = '123456789'37        self.digits = '123456789'38        self.grid = ["%s%s" % (row, col) for row, col in product(self.rows, self.cols)]39        self.rows_all_diff = [["%s%s" % (x, y) for x, y in product(row, self.cols)]40                              for row in self.rows]41        self.cols_all_diff = [["%s%s" % (x, y) for x, y in product(self.rows, col)]42                              for col in self.cols]43        self.block_all_diff = [["%s%s" % (row, col) for row in self.rows[i:i + 3] for col in self.cols[j:j + 3]]44                               for j in range(0, 9, 3)45                               for i in range(0, 9, 3)]46        self.total_diff = self.rows_all_diff + self.cols_all_diff + self.block_all_diff47    def add_constraint(self, variable1_key, variable2_key):48        self.C[(variable1_key, variable2_key)] = lambda x, y: x != y49    def get_constraint(self, variable1_key, variable2_key):50        return self.C[(variable1_key, variable2_key)]51    def add_variable(self, variable_key):52        if variable_key not in self.V.keys():53            self.V[variable_key] = set()54            self.D[variable_key] = []55    def add_domain(self, variable, domain: str):56        self.D[variable].append(domain)57    def get_domain(self, variable):58        return self.D[variable]59    def remove_domain(self, variable, domain):60        self.D[variable].remove(domain)61    def get_neighbour(self, Xi: str):  # ,Xj: str):62        for xi, xj in self.C.keys():63            if Xi == xi and xj not in self.V[Xi]:  # and xj not in self.V[Xi]:64                self.V[Xi] = self.V[Xi].union({xj})65        return self.V[Xi]66    def initial_config(self, config):67        for value, variable in zip(config, self.grid):68            self.add_variable(variable)69            self.A_partial[variable] = value70            if value == "0":71                for d in self.digits:72                    self.add_domain(variable, d)73            else:74                self.add_domain(variable, value)75    def initialize_C(self):76        count = 077        if self.V and self.D:78            for i in range(9):79                for j in range(1, 9):80                    for constr in self.total_diff:81                        if self.grid[count] in constr:82                            for c in constr:83                                if c != self.grid[count] \84                                        and (self.grid[count], c) not in self.C.keys() \85                                        and (c, self.grid[count]) not in self.C.keys():86                                    # print("Adding Constraint")87                                    self.add_constraint(self.grid[count], c)88                                    self.add_constraint(c, self.grid[count])89                    count += 190                count += 191    def ac3(self, D):92        q = queue.Queue()93        for arc in self.C.keys():94            q.put(arc)95        i = 096        while not q.empty():97            i += 198            Xi, Xj = q.get()99            # print(Xi, Xj)100            # print("%s before %s"%(Xi, D[Xi]))101            if self.revise(D, Xi, Xj):102                #print("%s after %s"%(Xi, D[Xi]))103                if len(D[Xi]) == 0:104                    return False105                for Xk in (self.get_neighbour(Xi) - {Xj}):106                    q.put((Xk, Xi))107        return True108    def revise(self, D: dict, Xi: str, Xj: str) -> bool:109        revised = False110        for x in D[Xi]:111            consistency = [self.C[(Xi, Xj)](x, y) for y in D[Xj]]112            if not any(consistency):113                D[Xi].remove(x)114                revised = True115        return revised116def back_tracking_search(csp):117    csp_copy = deepcopy(csp)118    csp_copy.ac3(csp_copy.D)119    return recursive_back_tracking({}, csp_copy, 0)120def recursive_back_tracking(assignment, csp, i):121    #print("Backtracking iter %i" % i)122    if test_goal(csp):123        return assignment, csp124    var = select_unassigned(csp.A_partial, csp.D, strategy="mrv")125    for value in csp.D[var]:126        A_ = deepcopy(csp.A_partial)127        D_ = deepcopy(csp.D)128        A_[var] = value129        D_[var] = [value]130        csp2 = deepcopy(csp)131        csp2.A_partial = A_132        csp2.D = D_133        if csp.ac3(D_):134            assignment[var] = value135            result = recursive_back_tracking(assignment, csp2, i + 1)136            if result:137                return result138            assignment[var] = ""139    return False140def select_unassigned(A_partial, D:dict, strategy="mrv"):141    if strategy == "mrv":142        mrv = None143        mrv_val = 10144        for key in A_partial:145            if A_partial[key] == "0":146                if len(D[key]) < mrv_val:147                    mrv = key148        return mrv149    else:150        for key in A_partial:151            if A_partial[key] == "0":152                return key153def complete(A):154    for a in A.keys():155        if A[a] == "0":156            return False157        else:158            return True159def test_goal(csp):160    for c in csp.D.keys():161        if len(csp.D[c]) != 1:162            return False163    return True164def check_sudokus():165    trues = []166    trues_bts = []167    with open("sudokus_start.txt", "r") as file:168        with open("sudokus_finish.txt", "r") as file_output:169            i = 0170            line = file.readline()171            while line:172                line_output = file_output.readline()173                print(i)174                print(line)175                i +=1176                csp = CSP()177                csp_bts = CSP()178                # print(line)179                csp.initial_config(line)180                csp_bts.initial_config(line)181                # print(csp.D)182                csp.initialize_C()183                csp_bts.initialize_C()184                # print(csp.C.keys())185                ac3 = csp.ac3(csp.D)186                all_ones = all([1 if len(csp.D[key]) == 1 else 0 for key in csp.D])187                trues.append(all_ones)188                assignment, csp_bts = back_tracking_search(csp_bts)189                bts_res = [False if int(output)!=int(*d) else True for output, d in zip(line_output, csp_bts.D.values())]190                if all(bts_res):191                    trues_bts.append(True)192                else:193                    trues_bts.append(False)194                print(trues)195                print(trues_bts)196                line = file.readline()197#check_sudokus()198sudoku_input = sys.argv[1]199csp = CSP()200csp.initial_config(sudoku_input)201csp.initialize_C()202csp_ac3 = deepcopy(csp)203ac3 = csp_ac3.ac3(csp_ac3.D)204all_ones = all([1 if len(csp_ac3.D[key]) == 1 else 0 for key in csp_ac3.D])205if os.path.exists("output.txt"):206    print("path exists")207    os.remove("output.txt")208if all_ones:209    with open("output.txt", "a") as file:210        solution = ""211        for value in csp_ac3.D.values():212            solution += "%i"%int(*value)213        solution += " AC3 \n"214        file.write(solution)215assignment, csp = back_tracking_search(csp=csp)216with open("output.txt", "a") as file:217    output = ""218    for o in csp.D.values():219        output += "%i" % int(*o)220    output += " BTS"...solvers.py
Source:solvers.py  
...66        self.__xmax = xmax67        self.__dx = dx68        # +2 to have ghost cells for the boundary conditions69        self.__space_steps = int((self.xmax - self.xmin) // self.dx + 2)70    def initialize_c(self):71        self.__c = np.zeros(shape=(self.space_steps, self.time_steps))72        self.__c[0, 0] = 173    def _create_matrices(self, t_step=0):74        r = self.dt / 2 / self.dx ** 275        self.__r = r76        self.__A = np.zeros(shape=(self.space_steps, self.space_steps))77        self.__B = np.zeros(shape=(self.space_steps, self.space_steps))78        # these two lines set the BC.79        # TODO: Verify these conditions. At the moment should be Dirichelet80        self.__A[0, 0] = 181        self.__A[self.space_steps - 1, self.space_steps - 1] = 182        for i in range(1, self.space_steps - 1):83            d_plus = (self.diff_coeff(self.c[i + 1, t_step]) + self.diff_coeff(self.c[i, t_step])) / 284            d_minus = (self.diff_coeff(self.c[i, t_step]) + self.diff_coeff(self.c[i - 1, t_step])) / 285            self.__A[i, i - 1] = -r * d_minus86            self.__A[i, i] = 1 + r * (d_plus + d_minus)87            self.__A[i, i + 1] = -r * d_plus88        self.__B[0, 0] = 189        self.__B[self.space_steps - 1, self.space_steps - 1] = 190        for i in range(1, self.space_steps - 1):91            d_plus = (self.diff_coeff(self.c[i + 1, t_step]) + self.diff_coeff(self.c[i, t_step])) / 292            d_minus = (self.diff_coeff(self.c[i, t_step]) + self.diff_coeff(self.c[i - 1, t_step])) / 293            self.__B[i, i - 1] = r * d_minus94            self.__B[i, i] = 1 - r * (d_plus + d_minus)95            self.__B[i, i + 1] = r * d_plus96        return self.__A, self.__B97    def solve_diffusion(self):98        for t in tqdm(range(1, self.time_steps), ncols=100):99            A, B = self._create_matrices()100            b = np.dot(B, self.c[:, t - 1])101            c = np.linalg.solve(A, b)102            self.__c[:, t] = c103        return self.c104if __name__ == '__main__':105    sim = Solver1D()106    sim.initialize_space(0, 10, 0.01)107    sim.initialize_time(0, 1, 0.002)108    sim.initialize_c()109    sim.diff_coeff = lambda x: 0.1 * np.exp(-0.1 * x)110    A, B = sim._create_matrices()111    print(sim.r)112    c = sim.solve_diffusion()113    plt.plot(c[1:, ::10])...pgel_sat.py
Source:pgel_sat.py  
...8def is_satisfiable(kb):9    return solve(kb)['satisfiable']10def solve(kb):11    C = initialize_C(kb)12    c = initialize_c(kb)13    d = initialize_d(kb)14    signs = initialize_signs(kb)15    trace(f'C:\n {C}')16    trace(f'c: {c}')17    trace(f'd: {d}')18    trace(f'signs: {signs}')19    lp = linprog.solve(c, C, d, signs)20    trace(str_lp(lp))21    i = 022    iteration_times = []23    while not is_min_cost_zero(lp):24        start = time.time()25        trace(f'\n\niteration: {i}')26        result = generate_column(kb, lp)27        if not result['success']:28            return {'satisfiable': False, 'iterations': i,29                    'iteration_times': iteration_times}30        trace(f'column {result["column"]}')31        column = result['column']32        C = np.column_stack((C, column))33        c = np.append(c, 0)34        lp = linprog.solve(c, C, d, signs)35        trace(str_lp(lp))36        i += 137        end = time.time()38        iteration_times += [end - start]39    assert_result(C @ lp.x, signs, d)40    return {'satisfiable': True, 'lp': lp, 'iterations': i,41            'iteration_times': iteration_times}42def initialize_C(kb):43    C_left = np.identity(kb.n + kb.k + 1)44    C_right = np.vstack((45        - np.identity(kb.n),46        kb.A,47        np.zeros(kb.n)48    ))49    return np.hstack((C_left, C_right))50def initialize_c(kb):51    c_left = np.ones(kb.n + kb.k + 1)52    c_right = np.zeros(kb.n)53    return np.hstack((c_left, c_right))54def initialize_d(kb):55    return np.hstack((np.zeros(kb.n), kb.b, 1))56def initialize_signs(kb):57    return ['==']*kb.n + kb.signs + ['==']58def is_min_cost_zero(lp):59    return isclose(lp.cost, 0, abs_tol=EPSILON)60def get_weights(lp):61    return np.array(lp.y)62def generate_column(kb, lp):63    weights = get_weights(lp)64    trace(f'weights {weights}')...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!!
