Best Python code snippet using fMBT_python
first-missing-positive.py
Source:first-missing-positive.py  
1from typing import List2class Solution:3    def __init__(self):4        pass5    def firstMissingPositive(self, nums: List[int]) -> int: 6        n = len(nums)7        for i in range(0, n):8            if nums[i] == i + 1:9                continue10            if nums[i] <= 0:11                continue12            if nums[i] >= n + 1:13                nums[i] = 014                continue15            value = nums[i]16            nums[i] = 017            while True:18                newValue = nums[value - 1]19                nums[value - 1] = value 20                if newValue == value:21                    break22                if newValue >= n + 1:23                    break24                if newValue <= 0:25                    break26                value = newValue 27        for i in range(0, n):28            if nums[i] <= 0:29                return i + 130        return n + 1 31class Testing:32    def __init__(self):33        self.tests = []34    def setTestCheck(self, f):35        self.testCheck = f36    def addTestcase(self, test):37        self.tests.append(test)38    def runTest(self):39        for index, test in enumerate(self.tests):40            self.testCheck(index, test)41        pass42if __name__ == "__main__":43    # inititalize testing and solution44    testing = Testing()45    solution = Solution()46    # Add test here47    test = dict(48        In = [1, 2, 0],49        Out = 3,50    ) 51    testing.addTestcase(test)52    test = dict(53        In = [3, 4, -1, 1],54        Out = 2,55    ) 56    testing.addTestcase(test)57    58    test = dict(59        In = [7, 8, 9, 11, 12],60        Out = 1,61    ) 62    testing.addTestcase(test)63    test = dict(64        In = [1],65        Out = 2,66    ) 67    testing.addTestcase(test)68    test = dict(69        In = [1, 1],70        Out = 2,71    ) 72    testing.addTestcase(test)73    # Set test check74    def testCheck(idTest, test):75        Input = test["In"]76        Out = test["Out"]77        ans = test["Out"] # TODO: Need to calculate the actual ans in the below code78        # Logic test starts here79        80        ans = solution.firstMissingPositive(Input)81        # Logic test ends here82        if ans == Out:83            print(f"Test {idTest}: Correct Answer")84        else:85            print(f"Test {idTest}: Wrong Answer")86            print(f"Expected: {Out}")87            print(f"Actual: {ans}")88        print()89    testing.setTestCheck(testCheck)90    # run testing...longest-valid-parentheses.py
Source:longest-valid-parentheses.py  
1class Solution:2    def __init__(self):3        pass4    5    def longestValidParentheses(self, s: str) -> int:6        n = len(s)7        dp = [0 for i in range(n + 1)]8        ans = 09        for i in range(1, n+1):10            if (s[i - 1] == '('):11                continue12            if (s[i - 1] == ')'):13                if i == 1:14                    continue15                if (s[i - 2] == '('):16                    dp[i] = dp[i - 2] + 217                else:18                    if dp[i - 1] == 0:19                        continue20                    else:21                        pos = i - 2 - dp[i - 1]22                        if pos < 0:23                            continue24                        if s[pos] == '(':25                            dp[i] = dp[i - 1] + 2 + dp[pos]26                ans = max(ans, dp[i])27        return ans28class Testing:29    def __init__(self):30        self.tests = []31    def setTestCheck(self, f):32        self.testCheck = f33    def addTestcase(self, test):34        self.tests.append(test)35    def runTest(self):36        for index, test in enumerate(self.tests):37            self.testCheck(index, test)38        pass39if __name__ == "__main__":40    # inititalize testing and solution41    testing = Testing()42    solution = Solution()43    # Add test here44    test = dict(45        In = "(()",46        Out = 2,47    ) 48    testing.addTestcase(test)49    test = dict(50        In = "",51        Out = 0,52    ) 53    testing.addTestcase(test)54    55    test = dict(56        In = ")()())",57        Out = 4,58    ) 59    testing.addTestcase(test)60    test = dict(61        In = "(()))())(",62        Out = 4,63    ) 64    testing.addTestcase(test)65    test = dict(66        In = "()(())", 67        Out = 6,68    ) 69    testing.addTestcase(test)70 71    # Set test check72    def testCheck(idTest, test):73        Input = test["In"]74        Out = test["Out"]75        # Logic test starts here76        77        ans = solution.longestValidParentheses(Input)78        # Logic test ends here79        if ans == Out:80            print(f"Test {idTest}: Correct Answer")81        else:82            print(f"Test {idTest}: Wrong Answer")83            print(f"Expected: {Out}")84            print(f"Actual: {ans}")85        print()86    testing.setTestCheck(testCheck)87    # run testing...generate.py
Source:generate.py  
...9parser.add_argument("out")10args = parser.parse_args()11Case = namedtuple('Case', ['name', 'data'])12testCases = []13def addTestCase(name, data):14    testCases.append(Case(name, data))15class Data(object):16    def __init__(self, w, h, x, y):17        super(Data, self).__init__()18        self.w = w19        self.h = h20        self.x = x21        self.y = y22    def asPython(self, h5, name):23        h5.create_dataset(name, (self.w, self.h))24        h5[name][...] = np.linspace(self.x, self.y, self.w * self.h).reshape(self.w, self.h)25    def asLua(self):26        out = ""27        out += "torch.linspace(%s, %s, %s)" % (self.x, self.y, self.w * self.h)28        out += ":resize(%s, %s):float()" % (self.w, self.h)29        return out30def luaDefinition(data):31    return "return " + luaDefinitionHelper(data, 0)32def luaDefinitionHelper(data, level):33    text = ""34    indent = "    "35    if isinstance(data, dict):36        text = "{\n"37        for k, v in data.iteritems():38            text += indent * (level + 1) + k + " = " + luaDefinitionHelper(v, level + 1) + ",\n"39        text += indent * level + "}"40    else:41        text += data.asLua()42    return text43def writeH5(h5, data):44    for k, v in data.iteritems():45        if isinstance(v, dict):46            group = h5.create_group(k)47            writeH5(group, v)48            continue49        v.asPython(h5, k)50addTestCase('empty', {})51addTestCase('oneTensor', { 'data' : Data(10, 10, 0, 100) })52addTestCase('twoTensors', { 'data1' : Data(10, 10, 0, 100), 'data2' : Data(10, 10, 0, 10) })53addTestCase('twoTensorsNested', { 'group' : { 'data' : Data(10, 10, 0, 100) } })54for case in testCases:55    print("=== Generating %s ===" % (case.name,))56    h5file = h5py.File(os.path.join(args.out, case.name + ".h5"), 'w')57    writeH5(h5file, case.data)58    luaFilePath = os.path.join(args.out, case.name + ".lua")59    with open(luaFilePath, 'w') as luaFile:...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!!
