【发布时间】:2023-01-19 14:38:53
【问题描述】:
代码:1
class Solution:
def firstElementKTime(self, a, n, k):
# code here
countDict = {}
for i in a:
if (a[i] in countDict):
countDict[a[i]] = countDict[a[i]] + 1
else:
countDict[a[i]] = 1
for i in a:
if countDict[a[i]] == k:
return a[i]
return -1
代码1的错误: 追溯(最近一次通话): 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 40 行,位于 主要的() 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 34 行,在 main 打印(ob.firstElementKTime(a,n,k)) 文件“/home/91ded90adaf6c5d579e2dbec3cedff79.py”,第 9 行,在 firstElementKTime 中 如果(countDict 中的 a[i]): IndexError:列表索引超出范围
代码:2
countDict = {}
for i in range(0, len(a)):
if a[i] in countDict:
countDict[a[i]] = countDict[a[i]] + 1
else:
countDict[a[i]] = 1
i = i + 1
for i in a:
if countDict[a[i]] == k:
return a[i]
return -1
没有错误:
我希望上述代码中的行为相同..
【问题讨论】:
标签: python python-3.x list for-loop