what is the mechanism for `def twoSum(self, nums: List[int], target: int) -> List[int]:` in python 3:

12,294

Solution 1

from typing import List

def twoSum(nums: List[int], target: int) -> List[int]:
    print(nums, target)

Link: https://docs.python.org/3/library/typing.html

Note The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.

Link: https://code.visualstudio.com/docs/python/linting

Solution 2

Python has introduced type hinting, which mean we could hinting the type of variable, this was done by doing variable: type (or parameter: type), so for example target is a parameter, of type integer.

the arrow (->) allows us to type hint the return type, which is a list containing integers.

from typing import List
Vector = List[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

In the function greeting, the argument name is expected to be of type str and the return type str. Subtypes are accepted as arguments.

def greeting(name: str) -> str:
    return 'Hello ' + name

Documentation : https://docs.python.org/3/library/typing.html

Solution 3

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

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
            for i in range(len(nums)):
                for j in range(i+1,len(nums)):
                    if target == nums[i]+nums[j]:
                        return [i,j]
                    
                    
num = [1,2,3,4,5,6,7,8,9,10]
target = 8

s = Solution()
print(s.twoSum(num,target))

#output [0,6]

Share:
12,294

Related videos on Youtube

jason
Author by

jason

Updated on July 01, 2022

Comments

  • jason
    jason almost 2 years

    Ifound the code as follow in python3:

    def twoSum(self, nums: List[int], target: int) -> List[int]:
        return sum(nums)
    

    As I know for python def, we only need follow:

    def twoSum(self, nums, target):
        return sum(nums)
    

    what is the nums: List[int], target: int and ->List[int] means? Are those new features of python 3? I never see those.

    Thanks,

  • Marslo
    Marslo almost 4 years
    after used from typing import List, I still encounter the issue for target: int: TypeError: twoSum() missing 1 required positional argument: 'target'; any ideas?