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

Viewed 19311

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,

4 Answers

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]

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

It's a static typing in python for type checking. It allows you to define the type of input parameters and returns so that certain incompatibilities are dealt with beforehand. They are only annotations, not an actual static typing though. Check mypy package for more.

Related