Best Python code snippet using avocado_python
advent.py
Source:advent.py  
1import os2import re3import copy4import math567def mostLikely2SplitsFirst(remainingString):89    ps = range(1,len(remainingString))10    average = sum(ps) / len(ps)11    pairs = []12    for p in ps:13        pairs.append((p,abs(average-p)))1415    pairs.sort(key=lambda x: x[1])16    sortedValues = []17    for p in pairs:18        sortedValues.append(p[0])19    return sortedValues202122def testAllPossible2Splits(remainingString,ruleLeft,ruleRight,recursionControl,ruleStuct):23    24    ## if ruleLeft or ruleRight == 12 then only split left or right by 125    ##  if ruleLeft or ruleRight == 106 then only split left or right by 126    27    if len(remainingString) < 2: 28        return False2930    foundMatch = False3132    rangeA = []3334    if ruleLeft == 12:35        rangeA = [1]36    elif ruleRight == 12:37        rangeA = [len(remainingString)-1]38    elif ruleLeft == 106:39        rangeA = [1]40    elif ruleRight == 106:41        rangeA = [len(remainingString)-1]42    else:43        rangeA = mostLikely2SplitsFirst(remainingString)4445    for splitPosition in rangeA:#range(1,len(remainingString)):46        leftStr = remainingString[0:splitPosition]47        assert len(leftStr) > 048        rightStr = remainingString[splitPosition:len(remainingString)]49        assert len(rightStr) > 050        remade = leftStr+rightStr51        assert remade == remainingString52        canMatchLeft = canIMatchThisStringForThisRule(leftStr,ruleLeft,recursionControl,ruleStuct)53        if canMatchLeft:54            canMatchRight = canIMatchThisStringForThisRule(rightStr,ruleRight,recursionControl,ruleStuct)55            if (canMatchRight):56                return True57    return foundMatch5859def testAllPossible3Splits(remainingString,ruleA,ruleB,ruleC,recursionControl,ruleStuct):60    foundMatch = False61    62    if len(remainingString) < 3: 63        return False6465    for splitPositionA in range(1,len(remainingString)-2):66        aStr = remainingString[0:splitPositionA]67        for splitPositionB in range(splitPositionA+1,len(remainingString)):68            bStr = remainingString[splitPositionA:splitPositionB]69            cStr = remainingString[splitPositionB:len(remainingString)]70            assert len(aStr) > 071            assert len(bStr) > 072            assert len(cStr) > 073            assert aStr+bStr+cStr == remainingString7475            canMatchA = canIMatchThisStringForThisRule(aStr,ruleA,recursionControl,ruleStuct)76            if canMatchA:77                canMatchB = canIMatchThisStringForThisRule(bStr,ruleB,recursionControl,ruleStuct)78                if (canMatchB):79                    canMatchC = canIMatchThisStringForThisRule(cStr,ruleC,recursionControl,ruleStuct)80                    if (canMatchC):81                        return True82    return foundMatch83848586def canIMatchThisStringForThisRule(remainingString,ruleN,recursionControl,ruleStuct):87    assert ruleN in ruleStuct88    choices = ruleStuct[ruleN]89    # No rules match to empty90    91    foundMatch = False9293     # If rule has one option94    if len(choices) == 1:95        parts = choices[0]96        # if option has one part97        if len(parts) == 1:98            # if part it terminal, return character99            if parts[0] == -1:100                foundMatch = "a" == remainingString101                #print("Match %s to rule %d is %s"%(remainingString,ruleN,foundMatch))102                return foundMatch103            elif parts[0] == -2:104                foundMatch = "b" == remainingString105                #print("Match %s to rule %d is %s"%(remainingString,ruleN,foundMatch))106                return foundMatch107    108109    for choice in choices:110        parts = choice111        nParts = len(parts)112        assert nParts < 4113        assert nParts > 0114        # There is 1,2 or 3 parts to this choice115        if nParts == 1:116            if canIMatchThisStringForThisRule(remainingString,parts[0],recursionControl,ruleStuct):117                foundMatch = True118                break119        elif nParts == 2:120            if testAllPossible2Splits(remainingString,parts[0],parts[1],recursionControl,ruleStuct):121                foundMatch = True122                break123        elif nParts == 3:124            if testAllPossible3Splits(remainingString,parts[0],parts[1],parts[2],recursionControl,ruleStuct):125                foundMatch = True126                break127128    #print("Match %s to rule %d is %s"%(remainingString,ruleN,foundMatch))129130    return foundMatch131132133134def testIsMessagesValid(ruleStruct,message):135    recursionControl = {}136    return canIMatchThisStringForThisRule(message,0,recursionControl,ruleStruct)137138def testAllMessagesAndCountValid(ruleStruct,messages):139    validMessageCount = 0140    msgChecked = 0141    for message in messages:142        print("Checking message %d"%(msgChecked))143        msgChecked = msgChecked + 1144        if testIsMessagesValid(ruleStruct,message):145            validMessageCount = validMessageCount + 1146    return validMessageCount147148def processLineOfInputIntoMessageStruct(line,messages):149    # ababbb150    messages.append(line.strip())151152def processLineOfInputIntoRuleStruct(line,rules):153    # "1: 2 3 | 3 2"154    # A is -1155    # B is -2156    partsA = line.split(":")                # ["1","2 3 | 3 2"]157    assert len(partsA) == 2158    partsB = partsA[1].strip().split("|")   # '["2 3","3 2"]159    ruleInt = int(partsA[0].strip())160    for optionsStr in partsB:161        optionIntArray = []162        rulesInOption = optionsStr.strip().split(" ") # ["2","3"]163        for optionStr in rulesInOption:164            if optionStr.strip() == "\"a\"":165                optionIntArray.append(-1)166            elif optionStr.strip() == "\"b\"":167                optionIntArray.append(-2)168            else:169                optionIntArray.append(int(optionStr))170        if ruleInt not in rules:171            rules[ruleInt] = []172        rules[ruleInt].append(optionIntArray)173174175def processInputFile(filePath):176    177    rules = {}178    messages = []179    if os.path.exists(filePath):180        f = open(filePath, "r")181        loadingMessages = False182        for x in f:183            if x == "\n":184                loadingMessages = True185                continue186            if loadingMessages:187                processLineOfInputIntoMessageStruct(x,messages)188            else:189                processLineOfInputIntoRuleStruct(x,rules)190        f.close()191    else :192        print("%s does not exist"%(filePath))193194    return (rules,messages)195196def getInputPath():197    return os.path.join(os.path.dirname(__file__),"input.txt")198199200def mainTask():201    input_path = getInputPath()202    rules, messages = processInputFile(input_path)203    count = testAllMessagesAndCountValid(rules,messages)204    print(200+count) # I didn't recheck all the messages that passed in part a - they will still pass in part b205206if __name__ == "__main__":207
...solution.py
Source:solution.py  
1from collections import defaultdict2def boggleBoard(board, words):3    letter_coords = defaultdict(list)4    5    max_row = len(board)6    max_col = len(board[0])7    8    for row in range(max_row):9        for col in range(max_col):10            letter = board[row][col]11            letter_coords[letter].append( (row, col) )12    13    def foundmatch(word, coord, idx=0, visited=None) -> bool:14        if not visited:15            visited = set()16        17        if word[idx] == board[coord[0]][coord[1]]:18            19            if idx == len(word)-1:20                return True21            new_idx = idx+122            new_visited = visited | {coord}23            options = []24            25            # up; row + 126            up = (coord[0]+1, coord[1])27            if up[0] < max_row and up not in visited:28                options.append(foundmatch(word, up, new_idx, new_visited))29                30            # down; row - 131            down = (coord[0]-1, coord[1])32            if down[0] > -1 and down not in visited:33                options.append(foundmatch(word, down, new_idx, new_visited))34                35            # left; col - 136            left = (coord[0], coord[1]-1)37            if left[1] > -1 and left not in visited:38                options.append(foundmatch(word, left, new_idx, new_visited))39            40            # right; col + 141            right = (coord[0], coord[1]+1)42            if right[1] < max_col and right not in visited:43                options.append(foundmatch(word, right, new_idx, new_visited))44            45            """46                # top-left; row+1, col-147                topleft = (coord[0]+1, coord[1]-1)48                if topleft[0] < max_row and topleft[1] > -1 and topleft not in visited:49                    options.append(foundmatch(word, topleft, new_idx, new_visited))50                    51                # top-right; row+1, col+152                topright = (coord[0]+1, coord[1]+1)53                if topright[0] < max_row and topright[1] < max_col and topright not in visited:54                    options.append(foundmatch(word, topright, new_idx, new_visited))55                    56                # bottom-left; row-1, col-157                bottomleft = (coord[0]-1, coord[1]-1)58                if bottomleft[0] > -1 and bottomleft[1] > -1 and bottomleft not in visited:59                    options.append(foundmatch(word, bottomleft, new_idx, new_visited))60                    61                # bottom-right; row-1, col+162                bottomright = (coord[0]-1, coord[1]+1)63                if bottomright[0] > -1 and bottomright[1] < max_col and bottomright not in visited:64                    options.append(foundmatch(word, bottomright, new_idx, new_visited))65            """66                67            return any(options)68            69        return False70    71    def found(word, starting_coords) -> bool:72        for coord in starting_coords:73            if foundmatch(word, coord):74                return True75        return False76    77    return [ 78        word for word in words79        if found(word, letter_coords[ word[0] ])80    ]81class Solution:82    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:...79_WordSearch.py
Source:79_WordSearch.py  
1//79)Word search23class Solution {4public:5    bool exist(vector<vector<char>>& board, string word) {6        if(word.empty() or board.empty()){7            return false;8            9        }10        bool foundMatch=false;11        for(int i=0;i<board.size();i++){12            for(int j=0;j<board[0].size();j++){13                if(board[i][j]==word[0]){14                    searchWord(word,{},board,0,i,j,foundMatch);15                }16                if(foundMatch){17                    return foundMatch;18                }19            }20        }21        return foundMatch;22    }23    void searchWord(const std::string&word,24                   std::string currentWord,25                   std::vector<std::vector<char>>& board,26                   int index,27                   int i,28                   int j,29                   bool& foundMatch)30    {31        if(currentWord.size()==word.size()){32            foundMatch=true;33            return;34        }35        if(i<0 or j<0 or i>=board.size() or j>=board[0].size() or board[i][j]!=word[index] or foundMatch)36            return;37        currentWord+=word[index];38        char temp=board[i][j];39        board[i][j]=' ';40        searchWord(word,currentWord,board,index+1,i+1,j,foundMatch);41        searchWord(word,currentWord,board,index+1,i-1,j,foundMatch);42        searchWord(word,currentWord,board,index+1,i,j+1,foundMatch);43        searchWord(word,currentWord,board,index+1,i,j-1,foundMatch);44        board[i][j]=temp;45        46    }
...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!!
