I am getting a Error in this program with output

From the error output, the leetcode driver program appears to be wanting to call your code with:

ret = Solution().twoSum(param_1, param_2)

In other words, it wants to construct your class with no parameters, then call a specific function in your class to do the work, passing the parameters into that function.

That means you’ll have to provide something like:

class Solution:
    def __init__(self):

    def twosum(self, nums, target):
        # Do your grunt work here.

And, if you want to use that exception, it should be inside the twosum function. The way you have it now is that the try/except is active during creation of the twosum function, not while running the function.

Additionally, you should get rid of, or adjust, your own driver code – that’s why you’re seeing the output you expect. But leetcode doesn’t want you to do that, it just wants you to provide the class so its driver can call it.

There’s a good chance it will simply import your file then call your function, so you can use the __name__ trick to use your driver code if you run it normally, or theirs if they import it.

With all that, you’ll probably end up with something like:

class Solution:
    def __init__(self):

    def twosum(self, nums, target):
        if  2 <= len(nums) <= 10**5:
            for x in nums:
                for y in nums:
                    if y != x and x+y == target:
                        solution = []
                        return solution

if __name__ == "__main__": # don't run if you get imported.
    nums = [1,2,3,4,5,6]
    target = 4
    demo = Solution(nums, target)

Keep in mind I have no idea if your twosum function is doing what it’s meant to do, I just tidied up the unnecessary stuff like break after return. But that should be a good basis for testing your code based on what leetcode needs from you.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top