Home > Software design >  Why class without __init__ method? [closed]
Why class without __init__ method? [closed]

Time:09-22

I don't understand why there is not an __init__() method.

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

Code I was given:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:

Code I developed:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        i = 0
        while i < len(nums) - 1:
            j = i   1
            while j < len(nums):
                if nums[i]   nums[j] == target:
                    return[i, j]
                j  = 1
            i  = 1

CodePudding user response:

The code you are given is an artifact of a code-challenge website like LeetCode, which (for some reason) requires solutions in the form of a class named Solution and a method with a given name. The class is likely not instantiated, or if it is, no initialization is required, because all the information needed by twoSum is passed an an argument. Your code will likely be called with something like

a = Solution()
assert a.twoSum(test_input1a, test_input1b) == solution1
assert a.twoSum(test_input2a, test_input2b) == solution2
# etc

This is not how you would typically design a class. If the class has only one method (in addition to __init__ or not), it's typically better to write a simple function.

  • Related