【问题标题】:what is the mechanism for `def twoSum(self, nums: List[int], target: int) -> List[int]:` in python 3:`def twoSum(self, nums: List[int], target: int) -> List[int]:` 在 python 3 中的机制是什么:
【发布时间】:2019-10-31 06:54:47
【问题描述】:

我在python3中找到如下代码:

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

据我所知,python def,我们只需要关注:

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

nums: List[int], target: int->List[int] 是什么意思?这些是python 3的新功能吗?我从没见过那些。

谢谢,

【问题讨论】:

    标签: python-3.x function arguments


    【解决方案1】:
    from typing import List
    
    def twoSum(nums: List[int], target: int) -> List[int]:
        print(nums, target)
    

    链接:https://docs.python.org/3/library/typing.html

    注意 Python 运行时不强制执行函数和变量类型注释。它们可供第三方工具使用,例如类型检查器、IDE、linter 等。

    链接:https://code.visualstudio.com/docs/python/linting

    【讨论】:

    • 使用from typing import List后,我仍然遇到target: int的问题:TypeError: twoSum() missing 1 required positional argument: 'target';有什么想法吗?
    【解决方案2】:

    Python 引入了类型提示,这意味着我们可以提示变量的类型,这是通过执行变量:类型(或参数:类型)来完成的,例如 target 是一个参数,类型为整数。

    箭头 (->) 允许我们输入提示返回类型,它是一个包含整数的列表。

    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])
    

    在函数greeting中,参数名称应为str类型,返回类型为str。接受子类型作为参数。

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

    文档:https://docs.python.org/3/library/typing.html

    【讨论】:

      【解决方案3】:

      给定一个整数数组 nums 和一个整数目标,返回这两个数字的索引,使它们相加为目标。

      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))
      

      #输出[0,6]

      【讨论】:

        【解决方案4】:

        这是python中用于类型检查的静态类型。它允许您定义输入参数和返回的类型,以便预先处理某些不兼容性。它们只是注释,而不是实际的静态类型。查看 mypy 包了解更多信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多