Python 3 List Type errors All In One
Python 3 List Type errors All In One
Python 3.9.x+
error
NameError: name 'List' is not defined
class Solution:
# ❌ NameError: name 'List' is not defined
def twoSum(self, nums: List[int], target: int) -> List[int]:
arr = []
for i, n in enumerate(nums):
v = target - n
for j, m in enumerate(nums):
if(i != j and v == m):
arr.append(i)
arr.append(j)
break
return arr
# test cases
t1 = [[2,7,11,15], 9]
t2 = [[3,2,4], 6]
t3 = [[3,3], 6]
tests = [t1, t2, t3]
r1 = [0,1]
r2= [1,2]
r3 = [0,1]
results = [r1, r2, r3]
def test():
for index, test in enumerate(tests):
r = Solution.twoSum(test)
result = results[index]
if(str(r) == str(result)):
print("passed ✅", index)
else:
print("failed ❌", index, test)
"""
$ py3 ./0001_two-sum.py
"""
solutions
from typing import List
def twoSum(self, nums: List[int], target: int) -> List[int]:
- python 3.9.x+
built-in
collection typeslist
def twoSum(self, nums: list[int], target: int) -> list[int]:
https://stackoverflow.com/questions/57505071/nameerror-name-list-is-not-defined
https://peps.python.org/pep-0585/
https://docs.python.org/3.9/whatsnew/3.9.html#type-hinting-generics-in-standard-collections
demos
# from ast import List
# ❌ TypeError: 'type' object is not subscriptable
# ✅ List types
from typing import List
class Solution:
# ❌ NameError: name 'List' is not defined
def twoSum(self, nums: List[int], target: int) -> List[int]:
# ✅ ✅ build-in collection types, list
# def twoSum(self, nums: list[int], target: int) -> list[int]:
print("\nnums =", nums)
print("target =", target)
arr = []
for i, n in enumerate(nums):
v = target - n
# ❌ AttributeError: 'list' object has no attribute 'slice'
# for j, m in enumerate(nums.slice(i)):
# for j, m in enumerate(nums[i:]):
for j, m in enumerate(nums):
if(i != j and v == m):
arr.append(i)
arr.append(j)
return arr
# test cases
t1 = [[2,7,11,15], 9]
t2 = [[3,2,4], 6]
t3 = [[3,3], 6]
tests = [t1, t2, t3]
r1 = [0,1]
r2= [1,2]
r3 = [0,1]
results = [r1, r2, r3]
def test():
# instance 实例化 ✅, fix: TypeError: twoSum() missing 1 required positional argument: 'target'
# https://stackoverflow.com/questions/17534345/why-do-i-get-typeerror-missing-1-required-positional-argument-self-trying
solution = Solution()
for index, test in enumerate(tests):
[arr, target] = test
# print("\narr, target = ", arr, target)
value = solution.twoSum(arr, target)
result = results[index]
# print("❓value =", value)
# print("result ", result)
if(str(value) == str(result)):
print("✅ passed", index)
else:
print("❌ failed", arr, result)
test()
"""
# https://leetcode.com/problems/two-sum/
$ py3 ./0001_two-sum.py
"""
https://leetcode.com/problems/two-sum/
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17593760.html
未经授权禁止转载,违者必究!