\`def twoSum(self, nums: List\[int\], target: int) -> List\[int\]:\` 在 python 3 中的机制是什么:

新手上路,请多包涵

I在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的新特性?我从没见过那些。

谢谢,

原文由 jason 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 954
2 个回答
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、linters 等。

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

原文由 Muhammad Rizwan 发布,翻译遵循 CC BY-SA 4.0 许可协议

给定一个整数数组 nums 和一个整数 target,返回两个数字的索引,使它们加起来等于 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))

#输出[0,6]

原文由 Mohammed Shakeeb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进