Best Python code snippet using gherkin-python
unittest_flaeche.py
Source:unittest_flaeche.py  
...109        myFlaeche = main.Flaeche(xdim=100, ydim=100, scale=1)110        self.assertEqual(myFlaeche.get_cell((15.5, 15.5)), (15, 15))111        self.assertEqual(myFlaeche.get_cell((15, 15)), (15, 15))112        # cells113        self.assertEqual(myFlaeche.get_cells((15.5, 15.5)), [(15, 15)])114        self.assertEqual(myFlaeche.get_cells((15, 15.5)), [(14, 15), (15, 15)])115        self.assertEqual(myFlaeche.get_cells((0, 15.5)), [(-1, 15), (0, 15)])116        self.assertEqual(myFlaeche.get_cells((15.5, 15)), [(15, 14), (15, 15)])117        self.assertEqual(myFlaeche.get_cells((15.5, 0)), [(15, -1), (15, 0)])118        self.assertEqual(119            myFlaeche.get_cells((15, 15)), [(14, 14), (14, 15), (15, 14), (15, 15)])120        self.assertEqual(121            myFlaeche.get_cells((15, 0)), [(14, -1), (14, 0), (15, -1), (15, 0)])122        self.assertEqual(123            myFlaeche.get_cells((0, 15)), [(-1, 14), (-1, 15), (0, 14), (0, 15)])124        self.assertEqual(myFlaeche.get_cells((0.5, 0.5)), [(0, 0)])125        # cells negative126        myFlaeche = main.Flaeche(xdim=100, ydim=100, scale=10)127        self.assertEqual(myFlaeche.get_cells((0.5, 0.5)), [(0, 0)])  # redunant128        self.assertEqual(myFlaeche.get_cells((-0.5, -0.5)), [(-1, -1)])129        self.assertEqual(myFlaeche.get_cells((-5, -5)), [(-1, -1)])130        self.assertEqual(myFlaeche.get_cells((-10, -5)), [(-2, -1), (-1, -1)])131        self.assertEqual(myFlaeche.get_cells((-5, 0)), [(-1, -1), (-1, 0)])132        self.assertEqual(133            myFlaeche.get_cells((0, 0)), [(-1, -1), (-1, 0), (0, -1), (0, 0)])134    def test_get_cell_and_sector(self):135        """test to vertify if a node is inside a Flaeche"""136        myFlaeche = main.Flaeche(xdim=100, ydim=100, scale=1)137        self.assertEqual(myFlaeche.get_cell_and_sector((1.5, 1.5), 0)[1],  0)138        self.assertEqual(139            myFlaeche.get_cell_and_sector((1.5, 1.5), 0.0001)[1],  0)140        self.assertEqual(141            myFlaeche.get_cell_and_sector((1.5, 1.5), 2 * math.pi / 16 / 2)[1],  0)142        self.assertEqual(myFlaeche.get_cell_and_sector(143            (1.5, 1.5), 2 * math.pi / 16 / 2 + 0.001)[1], 1)144        self.assertEqual(145            myFlaeche.get_cell_and_sector((1.5, 1.5), 2 * math.pi - 0.001)[1],  0)146        self.assertEqual(147            myFlaeche.get_cell_and_sector((1.5, 1.5), math.pi - 0.001)[1],  8)...main.py
Source:main.py  
...55        """56        copy_grid = Grid()57        copy_grid._cells = [row.copy() for row in self._cells]58        return copy_grid59    def get_cells(self):60        """61        Returns the matrix with the domains of all variables in the puzzle.62        """63        return self._cells64    def get_width(self):65        """66        Returns the width of the grid.67        """68        return self._width69    def read_file(self, string_puzzle):70        """71        Reads a Sudoku puzzle from string and initializes the matrix _cells.72        This is a valid input string:73        4.....8.5.3..........7......2.....6.....8.4......1.......6.3.7.5..2.....1.4......74        This is translated into the following Sudoku grid:75        - - - - - - - - - - - - -76        | 4 . . | . . . | 8 . 5 |77        | . 3 . | . . . | . . . |78        | . . . | 7 . . | . . . |79        - - - - - - - - - - - - -80        | . 2 . | . . . | . 6 . |81        | . . . | . 8 . | 4 . . |82        | . . . | . 1 . | . . . |83        - - - - - - - - - - - - -84        | . . . | 6 . 3 | . 7 . |85        | 5 . . | 2 . . | . . . |86        | 1 . 4 | . . . | . . . |87        - - - - - - - - - - - - -88        """89        i = 090        row = []91        for p in string_puzzle:92            if p == ".":93                row.append(self._complete_domain)94            else:95                row.append(p)96            i += 197            if i % self._width == 0:98                self._cells.append(row)99                row = []100    def print(self):101        """102        Prints the grid on the screen. Example:103        - - - - - - - - - - - - -104        | 4 . . | . . . | 8 . 5 |105        | . 3 . | . . . | . . . |106        | . . . | 7 . . | . . . |107        - - - - - - - - - - - - -108        | . 2 . | . . . | . 6 . |109        | . . . | . 8 . | 4 . . |110        | . . . | . 1 . | . . . |111        - - - - - - - - - - - - -112        | . . . | 6 . 3 | . 7 . |113        | 5 . . | 2 . . | . . . |114        | 1 . 4 | . . . | . . . |115        - - - - - - - - - - - - -116        """117        for _ in range(self._width + 4):118            print("-", end=" ")119        print()120        for i in range(self._width):121            print("|", end=" ")122            for j in range(self._width):123                if len(self._cells[i][j]) == 1:124                    print(self._cells[i][j], end=" ")125                elif len(self._cells[i][j]) > 1:126                    print(".", end=" ")127                else:128                    print(";", end=" ")129                if (j + 1) % 3 == 0:130                    print("|", end=" ")131            print()132            if (i + 1) % 3 == 0:133                for _ in range(self._width + 4):134                    print("-", end=" ")135                print()136        print()137    def print_domains(self):138        """139        Print the domain of each variable for a given grid of the puzzle.140        """141        for row in self._cells:142            print(row)143    def is_solved(self):144        """145        Returns True if the puzzle is solved and False otherwise.146        """147        for i in range(self._width):148            for j in range(self._width):149                if len(self._cells[i][j]) != 1:150                    return False151        return True152class VarSelector:153    """154    Interface for selecting variables in a partial assignment.155    Extend this class when implementing a new heuristic for variable selection.156    """157    def select_variable(self, grid: Grid) -> tuple[int, int]:158        pass159class FirstAvailable(VarSelector):160    """161    Naïve method for selecting variables; simply returns the first variable encountered whose domain is larger than one.162    """163    def select_variable(self, grid: Grid) -> tuple[int, int]:164        for i in enumerate(grid.get_cells()):165            for j in enumerate(i[1]):166                if len(j[1]) > 1:167                    return (i[0], j[0])168class MRV(VarSelector):169    """170    Implements the MRV heuristic, which returns one of the variables with smallest domain.171    """172    def select_variable(self, grid: Grid) -> tuple[int, int]:173        potential_variable = (-1, -1)174        current_min = 10175        for i in enumerate(grid.get_cells()):176            for j in enumerate(i[1]):177                domain_len = len(j[1])178                if domain_len > 1 and domain_len < current_min:179                    potential_variable = (i[0], j[0])180                    current_min = domain_len181        return potential_variable182class AC3:183    """184    This class implements the methods needed to run AC3 on Sudoku.185    """186    def remove_domain_row(self, grid, row, column):187        """188        Given a matrix (grid) and a cell on the grid (row and column) whose domain is of size 1 (i.e., the variable has its189        value assigned), this method removes the value of (row, column) from all variables in the same row.190        """191        variables_assigned = []192        for j in range(grid.get_width()):193            if j != column:194                new_domain = grid.get_cells()[row][j].replace(195                    grid.get_cells()[row][column], ""196                )197                if len(new_domain) == 0:198                    return None, True199                if len(new_domain) == 1 and len(grid.get_cells()[row][j]) > 1:200                    variables_assigned.append((row, j))201                grid.get_cells()[row][j] = new_domain202        return variables_assigned, False203    def remove_domain_column(self, grid, row, column):204        """205        Given a matrix (grid) and a cell on the grid (row and column) whose domain is of size 1 (i.e., the variable has its206        value assigned), this method removes the value of (row, column) from all variables in the same column.207        """208        variables_assigned = []209        for j in range(grid.get_width()):210            if j != row:211                new_domain = grid.get_cells()[j][column].replace(212                    grid.get_cells()[row][column], ""213                )214                if len(new_domain) == 0:215                    return None, True216                if len(new_domain) == 1 and len(grid.get_cells()[j][column]) > 1:217                    variables_assigned.append((j, column))218                grid.get_cells()[j][column] = new_domain219        return variables_assigned, False220    def remove_domain_unit(self, grid, row, column):221        """222        Given a matrix (grid) and a cell on the grid (row and column) whose domain is of size 1 (i.e., the variable has its223        value assigned), this method removes the value of (row, column) from all variables in the same unit.224        """225        variables_assigned = []226        row_init = (row // 3) * 3227        column_init = (column // 3) * 3228        for i in range(row_init, row_init + 3):229            for j in range(column_init, column_init + 3):230                if i == row and j == column:231                    continue232                new_domain = grid.get_cells()[i][j].replace(233                    grid.get_cells()[row][column], ""234                )235                if len(new_domain) == 0:236                    return None, True237                if len(new_domain) == 1 and len(grid.get_cells()[i][j]) > 1:238                    variables_assigned.append((i, j))239                grid.get_cells()[i][j] = new_domain240        return variables_assigned, False241    def pre_process_consistency(self, grid: Grid):242        """243        This method enforces arc consistency for the initial grid of the puzzle.244        The method runs AC3 for the arcs involving the variables whose values are245        already assigned in the initial grid.246        """247        initial_variables = set()248        for i in enumerate(grid.get_cells()):249            for j in enumerate(i[1]):250                if len(j[1]) == 1:251                    initial_variables.add((i[0], j[0]))252        self.consistency(grid, initial_variables)253    def consistency(self, grid, Q: Set[tuple[int, int]]) -> bool:254        """255        This is a domain-specific implementation of AC3 for Sudoku.256        It keeps a set of variables to be processed (Q) which is provided as input to the method.257        Since this is a domain-specific implementation, we don't need to maintain a graph and a set258        of arcs in memory. We can store in Q the cells of the grid and, when processing a cell, we259        ensure arc consistency of all variables related to this cell by removing the value of260        cell from all variables in its column, row, and unit.261        For example, if the method is used as a preprocessing step, then Q is initialized with262        all cells that start with a number on the grid. This method ensures arc consistency by263        removing from the domain of all variables in the row, column, and unit the values of264        the cells given as input. Like the general implementation of AC3, the method adds to265        Q all variables that have their values assigned during the propagation of the contraints.266        The method returns True if AC3 detected that the problem can't be solved with the current267        partial assignment; the method returns False otherwise.268        """269        while Q:270            variable = Q.pop()271            column_changed, column_failure = self.remove_domain_column(272                grid, variable[0], variable[1]273            )274            if column_failure:275                return False276            row_changed, row_failure = self.remove_domain_row(277                grid, variable[0], variable[1]278            )279            if row_failure:280                return False281            unit_changed, unit_failure = self.remove_domain_unit(282                grid, variable[0], variable[1]283            )284            if unit_failure:285                return False286            Q.update(column_changed + row_changed + unit_changed)287        return True288class Backtracking:289    """290    Class that implements backtracking search for solving CSPs.291    """292    ac = AC3()293    def search(self, grid: Grid, var_selector: VarSelector) -> Optional[Grid]:294        """295        Implements backtracking search with inference.296        """297        if grid.is_solved():298            return grid299        variable = var_selector.select_variable(grid)300        domain = grid.get_cells()[variable[0]][variable[1]]301        for value in domain:302            grid.get_cells()[variable[0]][variable[1]] = value303            cloned_grid = grid.copy()304            if self.ac.consistency(cloned_grid, set([variable])):305                rb = Backtracking().search(cloned_grid, var_selector)306                if rb is not None:307                    return rb308        return None309if __name__ == "__main__":310    # file = open("tutorial_problem.txt", "r")311    file = open("top95.txt", "r")312    problems = file.readlines()313    MRVTimes = []314    FATimes = []315    for p in problems:316        # Read problem from string...parse_data.py
Source:parse_data.py  
...5# è£
饰å¨ï¼è·åä¸ç¾¤åå
æ ¼çæ°æ®ï¼åå¨ä¸ä¸ªäºç»´åå
¸é6# axisä¸è¬æè´¦æ·æå¨çè½´7# sheet_name:表å; rows:è¡åå
¸; cols:ååå
¸ æ¯å¿
须忰ï¼acc_in_rowä¸ºè´¦å·æ¯å¦å¨æ¨ªè½´ï¼é»è®¤ä¸ºTrue8# -999为空å¼9def get_cells(obj):10    def wrap(self, *args, **kwargs):11        assert hasattr(obj, 'sheet_name'), 'æªæå®sheet_name'12        assert hasattr(obj, 'rows'), 'rowsåæ®µæªè®¾ç½®'13        assert hasattr(obj, 'cols'), 'colsåæ®µæªè®¾ç½®'14        sheet_name = getattr(obj, 'sheet_name')15        rows = getattr(obj, 'rows')16        cols = getattr(obj, 'cols')17        acc_in_row = getattr(obj, 'acc_in_row') if hasattr(obj, 'acc_in_row') else True  # é»è®¤è´¦æ·å¨è¡18        cells_data_type = getattr(obj, 'cells_data_type') if hasattr(obj, 'cells_data_type') else float  # é»è®¤æ°æ®ç±»å为float19        results = {}20        if acc_in_row:21            accs = rows22            fields = cols23        else:...world_test.py
Source:world_test.py  
...5    'Class for testing world behaviour.'6    def test_get_set_cells(self):7        'Test if world could give set of alived cells correctly'8        world = World()9        self.assertEqual(world.get_cells(), set())10        world = World({11            Cell(0, 0),12            Cell(3, 1),13            Cell(0, 0),14            })15        self.assertEqual(16            world.get_cells(),17            {18                Cell(3, 1),19                Cell(0, 0)})20    def test_empty_world(self):21        'Test case of empty field'22        world = World(23            {24            })25        world.next_state()26        result_cells = world.get_cells()27        self.assertEqual(len(result_cells), 0)28    def test_world_one_cell(self):29        'Test case of one alive cell in the game'30        world = World(31            {32                Cell(0, 0)33            })34        world.next_state()35        result_cells = world.get_cells()36        self.assertEqual(len(result_cells), 0)37    def test_world_square(self):38        'Test case of square of alive cell in the game'39        world = World(40            {41                Cell(0, 0, 'A'),42                Cell(1, 0, 'A'),43                Cell(0, 1, 'A'),44                Cell(1, 1, 'A'),45            })46        init_cells = world.get_cells()47        world.next_state()48        result_cells = world.get_cells()49        self.assertEqual(init_cells, result_cells)50    def test_world_line(self):51        'Test case of alived line 3x1 of cell in the game'52        horizontal_line = {53                Cell(-1, 1, 'C'),54                Cell(0, 1, 'C'),55                Cell(1, 1, 'C'),56            }57        vertical_line = {58                Cell(0, 0, 'C'),59                Cell(0, 1, 'C'),60                Cell(0, 2, 'C'),61            }62        world = World(63            vertical_line)64        world.next_state()65        result_cells = world.get_cells()66        self.assertEqual(horizontal_line, result_cells)67        world.next_state()68        result_cells = world.get_cells()69        self.assertEqual(vertical_line, result_cells)70    def test_world_A_cell_alone(self):71        'Test case of alived line 3x1 of cell in the game'72        before = {73                Cell(0, 0, 'A'),74            }75        empty_world = World({76            }).get_cells()77        world = World(78            before)79        world.next_state()80        result_cells = world.get_cells()81        self.assertEqual(empty_world, result_cells)82    def test_world_B_cell_alone(self):83        'Test case of alived line 3x1 of cell in the game'84        before = {85                Cell(0, 0, 'B'),86            }87        empty_world = World({88            }).get_cells()89        world = World(90            before)91        world.next_state()92        result_cells = world.get_cells()93        self.assertEqual(empty_world, result_cells)94    def test_world_C_cell_alone(self):95        'Test case of alived line 3x1 of cell in the game'96        before = {97                Cell(0, 0, 'C'),98            }99        empty_world = World({100            }).get_cells()101        world = World(102            before)103        world.next_state()104        result_cells = world.get_cells()105        self.assertEqual(empty_world, result_cells)106    def test_world_D_cell_alone(self):107        'Test case of alived line 3x1 of cell in the game'108        before = {109                Cell(0, 0, 'D'),110            }111        empty_world = World({112            }).get_cells()113        world = World(114            before)115        world.next_state()116        result_cells = world.get_cells()117        self.assertEqual(empty_world, result_cells)118    def test_world_with_all_cells(self):119        'Test case of alived line 3x1 of cell in the game'120        before = {121                Cell(0, 0, 'A'),122                Cell(1, 0, 'B'),123                Cell(2, 0, 'C'),124                Cell(3, 0, 'D'),125                Cell(4, 0, 'None'),126                Cell(1, 1, 'A'),127                Cell(2, 1, 'B'),128                Cell(3, 1, 'C'),129                Cell(4, 1, 'D'),130                Cell(5, 1, 'None'),131                Cell(2, 2, 'A'),132                Cell(3, 2, 'B'),133                Cell(4, 2, 'C'),134                Cell(5, 2, 'D'),135                Cell(6, 2, 'None'),136                Cell(3, 3, 'A'),137                Cell(4, 3, 'B'),138                Cell(5, 3, 'C'),139                Cell(6, 3, 'D'),140                Cell(7, 3, 'None'),141            }142        excpected_result = {143            Cell(1, 1, 'A'),144            Cell(2, 1, 'B'),145            Cell(2, 2, 'A'),146            Cell(3, 0, 'D'),147            Cell(3, 1, 'C'),148            Cell(3, 2, 'B'),149            Cell(4, 1, 'D'),150            Cell(4, 2, 'C'),151            Cell(5, 2, 'D'),152            }153        world = World(154            before)155        world.next_state()156        result_cells = world.get_cells()157        self.assertEqual(excpected_result, result_cells)158    def test_square_A(self):159        before = {160                Cell(0, 0, 'A'),161                Cell(1, 0, 'A'),162                Cell(1, 1, 'A'),163                Cell(0, 1, 'A'),164            }165        excpected_result = before166        world = World(167            before)168        world.next_state()169        result_cells = world.get_cells()170        self.assertEqual(excpected_result, result_cells)171        172    def test_square_B(self):173        before = {174                Cell(0, 0, 'B'),175                Cell(1, 0, 'B'),176                Cell(1, 1, 'B'),177                Cell(0, 1, 'B'),178            }179        excpected_result = before180        world = World(181            before)182        world.next_state()183        result_cells = world.get_cells()184        self.assertEqual(excpected_result, result_cells)185        186    def test_square_C(self):187        before = {188                Cell(0, 0, 'C'),189                Cell(1, 0, 'C'),190                Cell(1, 1, 'C'),191                Cell(0, 1, 'C'),192            }193        excpected_result = before194        world = World(195            before)196        world.next_state()197        result_cells = world.get_cells()198        self.assertEqual(excpected_result, result_cells)199        200    def test_square_D(self):201        before = {202                Cell(0, 0, 'D'),203                Cell(1, 0, 'D'),204                Cell(1, 1, 'D'),205                Cell(0, 1, 'D'),206            }207        excpected_result = before208        world = World(209            before)210        world.next_state()211        result_cells = world.get_cells()212        self.assertEqual(excpected_result, result_cells)213        214    def test_world_D_cell_with_unknown(self):215        'Test case of alived line 3x1 of cell in the game'216        before = {217                Cell(0, 0, 'D'),218                Cell(0, 1, 'None'),219            }220        empty_world = World({221            }).get_cells()222        world = World(223            before)224        world.next_state()225        result_cells = world.get_cells()226        self.assertEqual(empty_world, result_cells)227    def test_set_cells(self):228        world = World({})229        cells = {Cell(0, 0, 'A')}230        world.set_cells(cells)...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!!
